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"
.
链接:https://leetcode.com/problems/zigzag-conversion/#/description
4/4/2017
64ms, 50%
注意的问题:
1. 第3行的判断,需要包括空字符串,输出为1
2. 第6行,sb中每一个StringBuilder都需要初始化
3. 第15行同第3行,需要判断是否是空字符串 --〉更正,这是不需要的,去掉这个判断,运行时间减少25%
1 public class Solution { 2 public String convert(String s, int numRows) { 3 if (s.length() == 0 || s == null || numRows == 1) return s; 4 StringBuilder[] sb = new StringBuilder[numRows]; 5 int base = numRows + (numRows - 2); 6 for (int i = 0; i < sb.length; i++) sb[i] = new StringBuilder(); 7 8 for (int i = 0; i < s.length(); i++) { 9 int r = i % base; 10 if (r > base / 2) r = base - r; 11 sb[r].append(s.charAt(i)); 12 } 13 StringBuilder ret = new StringBuilder(); 14 for (int i = 0; i < sb.length; i++) { 15 ret.append(sb[i]); 16 } 17 return ret.toString(); 18 } 19 }
更多讨论:https://discuss.leetcode.com/category/14/zigzag-conversion