标签:
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 R
And 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"
.
开始采用了string.push_back,出现内存溢出,换为string+=就可以通过。
锯齿状走线,除去头尾都是step=2*(nROW-1);其他都为i,step-i,交替输入。
1 class Solution { 2 public: 3 string convert(string s, int numRows) { 4 int n=s.size(); 5 if(n<2) return s; 6 if(numRows==1) return s; 7 int step=(numRows-1)*2; 8 string res=""; 9 for(int j=0;j<numRows;j++) 10 { 11 int left=j; 12 int right=step-j; 13 if(right==step||left==right) 14 { 15 while(left<n) 16 { 17 res+=s[left]; 18 left+=step; 19 20 } 21 } 22 else 23 { 24 while(left<n||right<n) 25 { 26 if(left<n) 27 { 28 res+=s[left]; 29 left+=step; 30 31 } 32 if(right<n) 33 { 34 res+=s[right]; 35 right+=step; 36 37 } 38 } 39 } 40 } 41 42 return res; 43 } 44 };
标签:
原文地址:http://www.cnblogs.com/zl1991/p/4715286.html