6. ZigZag Conversion
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"
.
n=4时的走法是:
0 6 12
1 5 7 11 13
2 4 8 10 14
3 9 15
解法:
对于第一行与最后一行,间隔均为2*n-2.
对于中间的斜行,间隔为当前列j+(2n-2)-2i(i是行).
java实现:
1 public String convert(String s, int nRows) { 2 if(s == null || s.length()==0 || nRows <=0) 3 return ""; 4 if(nRows == 1) 5 return s; 6 7 StringBuilder res = new StringBuilder(); 8 int size = 2*nRows-2; 9 for(int i=0;i<nRows;i++){ 10 for(int j=i;j<s.length();j+=size){ 11 res.append(s.charAt(j)); 12 if(i != 0 && i != nRows - 1){//except the first row and the last row 13 int temp = j+size-2*i; 14 if(temp<s.length()) 15 res.append(s.charAt(temp)); 16 } 17 } 18 } 19 return res.toString(); 20 }