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)
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行和第numRows行,字符在原字符串的下标index=index+2*(numRows-1)
对于第i行(非第一行和非第numRows行),则要分为奇数列和偶数列分别处理。
当为奇数列时,index += 2*(numRows-i-1)
当为偶数列时,index += 2*i
class Solution {
public:
string convert(string s, int numRows) {
int i;
i=0;
string res="";
int len = s.length();
if(numRows <=1 || len <2)
return s;
if(numRows > len)
return s;
for(i=0;i<numRows;i++)
{
int index;
index = i;
res += s[index];
int k;
for(k=1;index<len;k++)
{
if(i==0 || i==numRows-1)
index += 2*(numRows-1);
else
{
if(k&0x1 == 1)
index+=2*(numRows-i-1);
else
index+=2*i;
}
if(index<len)
res += s[index];
}
}
return res;
}
};