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"
做法:按z字型读取的时候,我们可以直接推出每行字母间距的公式,比如说例子中的,一共三行时,第一行间字母间距为4,第二行中字母间距为2,最后一行也为4。再简单对比一下其他的情况可以发现,第一行和最后一行的字母间总有最大间距maxStep=2*(numRows-1)(除了第一行);而从第二行开始的第一个字母与下一个字母间距为maxStep-(j*2)(j代表当前的行数),然后第二个字母与第三个字母的间距为maxStep-step,下一次依然是这样。需要注意的是最后一行,此时的步长全部为maxStep,这时要记录下来已经到了最后一行了,否则程序会无穷无尽的做下去。
string convert(string s, int numRows) {
int n=s.length();
if(numRows<=1)return s;
string ans="";
int i=0,j=0;
int maxStep=2*(numRows-1);
int step=maxStep;
int isover=0;
while(j<numRows){
i=j++;
while(i<n){
ans+=s[i];
i+=step;
if(step!=maxStep)step=maxStep-step;
}
if(isover)return ans;
step=maxStep-2*j;
if(step==0){
step=maxStep;
isover=1;
}
}
return ans;
}