1. 题目
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. 思路
按规则计算每行的下标顺序进行打印即可。
首行和末行可以同质对待,但是会有下标重叠,进行一下特殊处理即可。
3. 代码
耗时:16ms
class Solution {
public:
string convert(string s, int numRows) {
int len = s.length();
if (numRows <= 1 || len <= numRows) {
return s;
}
string so;
so.resize(len);
so = "";
int l = numRows * 2 - 2;
for (int ri = 0; ri < numRows; ri++) {
int i = 0;
int last = -1;
while (true) {
int base = i * l;
int p1 = base + ri;
int p2 = base + l - ri ;
if (p1 < len && p1 != last) so += s[p1];
if (p2 < len && p2 != p1) so += s[p2];
i++;
last = p2;
if (p2 >= len) break;
}
}
return so;
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。