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"
.
将字符进行Z字型转换,然后进行存储,一开始没有想到什么好方法,看了下别人的实现,可以做的比较简单,每一行用一个字符串记录下来之后,然后拼接起来就可以,非满列字符串是有规律的,具体见下代码:
1 class Solution { 2 public: 3 string convert(string s, int numRows) { 4 vector<string> res; 5 res.resize(numRows); 6 string ret; 7 int gap = numRows - 2; 8 int i = 0, j; 9 while(i < s.size()){ 10 for(j = 0; i < s.size() && j < numRows; ++i, ++j) 11 res[j] += s[i]; 12 for(j = gap; i < s.size() && j > 0; ++i, --j) 13 res[j] += s[i]; 14 } 15 for(int k = 0; k < numRows; ++k){ 16 ret += res[k]; 17 } 18 return ret; 19 } 20 };