问题描述:
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”
我的解题思路:
这道题目就是简单的找数学规律的题目,没有什么技巧性可言。写好的程序如下:
class Solution {
public:
string convert(string s, int numRows) {
int len=s.length();int m = numRows;
if(m==1)
return s;
int zig_num = len/(2*numRows-2);
int remain_num = len % (2*numRows-2);
string res("");
for(int i=0;i<m;i++)
{
string tmp("");
for(int j=0;j<=zig_num;j++)
{
if(i==0||i==m-1)
{
if(i+j*(2*m-2)<len)
tmp=tmp+s[i+j*(2*m-2)];
}
else
{
if(i+j*(2*m-2)<len)
tmp=tmp+s[i+j*(2*m-2)];
if(2*m-2-i+j*(2*m-2)<len)
tmp=tmp+s[2*m-2-i+j*(2*m-2)];
}
}
res=res+tmp;
}
return res;
}
};