6. ZigZag Conversion
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 RAnd 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”.
所谓的zigzag pattern型就是指,我们以倒N型的顺序来读数。
三行的情况:
四行的情况:
我们输入的text是以这种模式来排布的,之后我们需要将其以横向的、从左到右的、我们习惯的阅读方式来从新排布,将其输出。
一种解题思路就是,我们使用数个字符串(设为row[n]),存下每一行的字符,最后将每行的字符串叠连起来,就是我们想要的结果。以一次下、一次上为一个单元(一共2*nRows-2个字符),这样我们就能算出每个输入的text中的每个字符分别对应某个单元的第几个字符,也就可以计算得到改字符的行数。也就是说,我们能够计算出text[i],text的第i个字符是属于第几行的,之后将其添加到row中。这样,我们只需要走一次text,就能够得到每行依此有哪些字符,之后将其首尾相连,得到的就是输出了。
参考代码如下:
class Solution {
public:
string convert(string s, int numRows) {
int len = s.length();
if(len <= 1 || numRows == 1)
return s;
string temp[numRows];
for(int i = 0; i < numRows; i++)
temp[i] = "";
for(int i = 0; i < len; i++) {
int index = i % (2*numRows-2);
if(index >= numRows)
index = 2 * numRows - 2 - index;
temp[index] += s[i];
}
string result = "";
for(int i = 0; i < numRows; i++)
result += temp[i];
return result;
}
};