LeetCode 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"
.
0 | 8 | 16 | |||||||||
1 | 7 | 9 | 15 | 17 | |||||||
2 | 6 | 10 | 14 | 18 | |||||||
3 | 5 | 11 | 13 | 19 | |||||||
4 | 12 | 20 |
分两次循环,第一次是列,第二次是斜线。
java需使用stringbuffer才不会超时,使用string超时了。
1 public class Solution { 2 public String convert(String s, int nRows) { 3 if (nRows==1) { 4 return s; 5 } 6 7 StringBuffer[] reBuffers=new StringBuffer[nRows]; 8 for (int i = 0; i < reBuffers.length; i++) { 9 reBuffers[i]=new StringBuffer(); 10 } 11 int i=0,j=0,C=nRows-2; 12 while (i<s.length()) { 13 for (j = 0; j<nRows&&i<s.length() ;j++) { 14 15 reBuffers[j].append(s.charAt(i++)); 16 17 } 18 19 for (j = C; i<s.length()&&j>0;j--) { 20 21 reBuffers[j].append(s.charAt(i++)); 22 23 } 24 25 } 26 27 StringBuffer res=new StringBuffer(); 28 for (int k = 0; k < nRows; k++) { 29 res.append(reBuffers[k]); 30 } 31 return res.toString(); 32 } 33 }