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, len-1行各个字符之间的间隔为2×nRows - 2
第1~len-2行之间会有两个固定间隔之间会有其他字符插入
规律:index + 2 * nRows - 2 * i - 2, 这里i是指行号
1 public class Solution { 2 public static String convert(String s, int nRows) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 if (s == null || s.length() == 0 || nRows <= 1) { 6 return s; 7 } 8 9 String result = generate(s, nRows); 10 return result; 11 } 12 13 private String generate(String s, int nRows) { 14 int len = s.length(); 15 StringBuffer buffer = new StringBuffer(); 16 int diff = 2 * nRows - 2; 17 for (int i = 0; i < nRows && i < len; i++) { 18 if (i == 0 || i == nRows - 1) { 19 buffer.append(s.charAt(i)); 20 int index = i; 21 while (index + diff < len) { 22 buffer.append(s.charAt(index + diff)); 23 index = index + diff; 24 } 25 // int tmp = i; 26 // while (i + diff < len) { 27 // buffer.append(s.charAt(i + diff)); 28 // i = i + diff; 29 // } 30 // i = tmp; 31 } else { 32 buffer.append(s.charAt(i)); 33 // int tmp = i; 34 int index = i; 35 while (2 * nRows - 2 * i - 2 + index < len 36 || index + diff < len) { 37 if(2 * nRows - 2 * i - 2 + index < len){ 38 buffer.append(s.charAt(2 * nRows - 2 * i - 2 + index)); 39 } 40 if (index + diff < len) { 41 buffer.append(s.charAt(index + diff)); 42 } 43 index += diff; 44 } 45 // while (2 * nRows - i - 2 < len || i + diff < len) { 46 // if (2 * nRows - i - 2 < len && 2 * nRows - i - 2 >= 0) { 47 // buffer.append(s.charAt(2 * nRows - i - 2)); 48 // } 49 // if (i + diff < len) { 50 // buffer.append(s.charAt(i + diff)); 51 // } 52 // i = i + diff; 53 // } 54 // i = tmp; 55 } 56 } 57 return buffer.toString(); 58 } 59 }
易错点:
1.i 是行号,不是字符串的index
2.特殊情况没有考虑:nRows == 1时,应当直接返回输入, 最初没有考虑==1的情况,出现死循环,导致Memory Limit Exceeded
3.当nRows > len 时,没有考虑,可能会出现下标溢出的情况