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".
找規律
一: 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 。。。
這到規律沒有?如果沒有找到, 你可以繼續寫5排的情況。很快你就可以找到規律。這是一個解決問題問題的方法。當我們遇到難纏的問題的時候,我們先考慮簡單的情形,看看能不能找到規律。這個題目,我們通過寫出來這些特殊情況,我們發現如下規律,這裏我們假設我們分成m排:
1 第i排從i開始
2 第i排兩個數的間隔是2(i-1),2(m-i)交替
下面的代碼通過了LeetCode online judge large
class Solution {
public:
string convert(string s, int nRows) {
string result;
if(nRows == 1) {
return s;
}
for(int i = 0; i < nRows; i++) {
int j = i;
bool flag = true;
while(j < s.size()) {
result.push_back(s[j]);
if(i == 0 || i == nRows - 1) {
j += 2 * (nRows - 1);
}
else {
if(flag) {
j += 2 * (nRows - 1 - i);
flag = false;
}
else {
j += 2 * i;
flag = true;
}
}
}
}
return result;
}
};