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"
.
首先理解题目ZigZag的意思。ZigZag Conversion即把字符串的字符按照Z字形重新排列,Z字形横过来看就是N字形。nRows=3的情况如上图所示,nRows=4应为
0 6
1 4 7
2 5 8
3 9
而不是
0 5
1 4 6
2 7
3 8
也就是中间应有nRows-2个数,而不是只有一个,这个一开始我理解错了。
那么特殊情况,nRows=1时,简单,直接返回s。
nRows=2时,
0 2
1 3
还是下面这种?
0 3
1 2 4
应该是第一种。
思路: 把s按照下标,以nRows+nRows-2为单位装入nRows个字符串数组中,然后挨个append到要输出的字符串后面即可。算法的复杂度为O(n)。
class Solution { public: string convert(string s, int nRows) { // Note: The Solution object is instantiated only once and is reused by each test case. if (nRows <= 1 ) return s; string* s_array=new string[nRows]; int n=nRows+nRows-2; int w=0; for(int i=0;i<s.length();i++){ w=nRows-1-abs(nRows-1-i%n); s_array[w].push_back(s[i]); } string str_result; for (int i = 0; i < nRows; ++i) str_result.append(s_array[i]); return str_result; } };