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".
题意:给定一个字符串,并给出显示的行数,把字符串按指定行数排成锯齿状,如串123456789ABC,行数为4,则排列顺序为
1 7
2 6 8 C
3 5 9 B
4 A
最终把字符按行返回,该例为返回17268C359B4A。
思路:根据上述图,能够找出规律。
z表示排列后的图形的转折点序号,如上图1为第1个转折点,4为第2 个转折点
k表示距离位置t最近的且比t大的转折点,如图中的1,4,7,A
由图可知,比位置t大且最近的转折点的序号为(t-1)/(nRows-1)+1
该转折点位置计算方式为k=1+(nRows-t)*z
则t位置的下一位置为t+(k-t)*2
实现:java
public class Solution {
public String convert(String s, int nRows) {
if(nRows<=1)return s;
String out="";
char[]c=s.toCharArray();
int z=0;
for(int i=1;i<=nRows;i++){
int t=i;
while(t<=s.length()){
z=(t-1)/(nRows-1)+1;
out+=c[t-1];
t+=(1+(nRows-1)*z-t)*2;
}
}
return out;
}
}