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 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".
P A H N
A P L S I I G
Y I R
通过分析可知,位于第一行和最后一行的间隔为interval = numRows + numRows -2 = 2*(numRows - 1)
现在分析其他行,我们发现,在其他行,假设行数为row(从0开始),第一个字符在原字符的row位置,而下一个字符在numsRows - row+ (numRows - row - 2) = 2*(numRows - row - 1),而下下个字符就在间隔interval处。
class Solution {
public:
string convert(string s, int numRows) {
if(numRows < 2)
return s;
int interval = (numRows - 1) <<1;
string res;
for(int i = 0; i < numRows; i++){
int dis = (numRows - 1 - i)<<1;
int j = i;
while(j < s.size()){
res += s[j];
if(dis != 0 && dis != interval && (j + dis) < s.size()){
res += s[j + dis];
}
j += interval;
}
}
return res;
}
};