ZigZag Conversion
The string "PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I RAnd then read line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
ZigZag的意思:
一: 2排的时候,1到n的排序
1 3 5 7 9 。。。
2 4 6 8 10 。。。
二: 3排的时候,1到n的排序
1 5 9 。。。
2 4 6 8 10 。。。
3 7 11 。。。
三: 4排的时候,1到n的排序
1 7 13 。。。
2 6 8 12 14 。。。
3 5 9 11 15 。。。
4 10 16 。。。
对于第一行(0)和最后一行(nRows-1),水平方向两个元素的间隔为:2(nRows-1)
对于第i行来说,水平方向的两个元素间隔为2(nRows-1-i),2(i)
1 class Solution { 2 public: 3 string convert(string s, int nRows) { 4 if(nRows==1) 5 { 6 return s; 7 } 8 string result; 9 int n=s.length(); 10 int step; 11 bool flag; 12 for(int i=0;i<nRows;i++) 13 { 14 int j=i; 15 flag=false; 16 while(j<n) 17 { 18 result.push_back(s[j]); 19 if(i==0||i==nRows-1) 20 { 21 step=2*(nRows-1); 22 } 23 else 24 { 25 if(flag==false) 26 { 27 step=2*(nRows-1-i); 28 flag=true; 29 } 30 else 31 { 32 step=2*i; 33 flag=false; 34 } 35 } 36 j+=step; 37 } 38 } 39 return result; 40 } 41 };