【LeetCode】6. ZigZag Conversion

来源:互联网 发布:datamap 软件 编辑:程序博客网 时间:2024/06/03 15:26

 


The string "PAYPALISHIRING" is written in azigzag pattern on a given number of rows like this: (you may want to displaythis pattern in a fixed font for better legibility)

P   A  H   N

AP L S I I G

Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make thisconversion given a number of rows:

stringconvert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

 

//这道题其实就是把字符串按照图示的方式打印出来,然后横向依次输出即可

//首先我们先分析第一行和最后一行

从P到A的距离为  2*nRow-2令其等于l。所以对于PAHM

我们依次   l=0;l=l+2*nRow-2;

在分析第二行  i指向纵向 

for(i=0;i<nRow;i++){

  //然后调整j,使其依次指向字母

   for(j=I;j<s.length();j=(j+2*nRow-2)){

//这时候先输出j=i时的字符

s.push_back(text[j]);

//如果位于不是第一行,最后一行并且j+l-2*i<text.length()

if(nRows!=i&&i!=0&&j+l-2*i<text.length()){

   //所以有

   s.push_back(text[j+l-2*i]);

 }

  }

}

所以代码如下:

class Solution {

public:

   string convert(string s, int numRows) {

       if(numRows<=1||s.length()<3||s.length()<=numRows)

       return s;

           string s2;

           int zigSpan=2*numRows-2;

           for (int i = 0; i < numRows; i++) 

       { 

           for (int j = i; j < s.length(); j+=zigSpan) 

           { 

                s2.push_back(s[j]); 

                //注意:推导出zigSpan+j-2i的数学公式,一点都不能错 

                if (i != 0 && i !=numRows-1 && zigSpan+j-2*i<s.length()) 

                { 

                   s2.push_back(s[zigSpan+j-2*i]); 

                } 

           } 

       } 

       return s2; 

       

    }

};

//本题注重的是数学推导,一定不要被锁形成的图形所迷惑!