題目:
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)
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"
.
答案:
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
string s_cp = s;
int p = 2 * (numRows - 1);
int k = 0;
for (int i = 0; i < numRows && k < s.size(); i++) {
for (int j = i; j < s.size(); j = j + p) {
s[k++] = s_cp[j];
int j2 = p - 2 * i + j;
if (i && i != numRows-1 && j2 < s.size()) {
s[k++] = s_cp[j2];
}
}
}
return s;
}
};
解析:
找規(guī)律帮掉。
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
==>
0 8 16 / 1 7 9 15 17 / 2 6 10 14 18 / 3 5 11 13 19 / 4 12 20