原题描述
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"
.
算法–找规律
没有什么算法可言,主要工作就是找规律
1. 所有行的重复周期是$2Rows - 2$
2. 对于在第一行和最后一行中间的行,还会重复一次,重复的位置距离起始字符为$2Rows - 2 - 2i$
C++代码如下:
class Solution {
public:
string convert(string s, int numRows) {
string ret = "";
int len = s.length();
if (numRows < 2) {
return s;
}
for (int i = 0; i < numRows; i++) {
for (int j = i; j < len; j+=(2*(numRows - 1))) {
ret += s[j];
if (i > 0 && i < (numRows - 1) && (j + 2*(numRows - 1) - 2*i) < len) {
ret += s[j + 2*(numRows - 1) - 2*i];
}
}
}
return ret;
}
};
Bug Free Procedure 从记事本直接写代码
2016.12.01 Bingo!!!一次性AC
2016.12.04 算法错误
1. 在添加第二个的规律项的时候记住,只针对于第一行和最后一行中间的行。
2016.12.14 Bingo!!!一次性AC