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”.
题意:输入一个字符串(之字形排列),一个行数,输出原按行排列的字符串。
class Solution {
public:
string convert(string s, int numRows) {
if(numRows <= 1) return s;
int len = s.length();
int row = 0, step = 1;
string *str = new string[numRows];
//模拟之字形过程
for (int i = 0; i < len; ++i) {
str[row].push_back(s[i]);
//从上往下,每次加一行
if (row == 0)
step = 1;
//从下往上,每次减一行
else if (row == numRows - 1)
step = -1;
row += step;
}
s.clear();
for (int j = 0; j < numRows; ++j)
s.append(str[j]);
delete[] str;
return s;
}
};
规律:第一行元素位置为0、2*(numRows-1)、4*(numRows-1)、……
最后一行:numRows-1、3*(numRows-1)、5*(numRows-1)、……
中间第i行:i-1,2*(numRows-1)-(i-1)、2*(numRows-1)、4*(numRows-1)-(i-1)、4*(numRows-1)……