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;
}
}