首页 > 代码库 > LeetCode ZigZag Conversion
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 NA P L S I I GY 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 }
LeetCode ZigZag Conversion
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。