1 public class Solution { 2 3 public static void main(String[] args) { 4 String s = "PAYPALISHIRING"; 5 String res = convert(s, 4); 6 System.out.println(res); 7 } 8 9 /** 10 * numRows=1和numRows=2为特殊情况 11 */ 12 public static String convert(String s, int numRows) { 13 String res = ""; 14 int l = s.length(); 15 if (l == 0) { 16 return ""; 17 } 18 19 if (l > 0 && l <= numRows) { 20 return s; 21 } 22 23 if (numRows == 1) { 24 return s; 25 } 26 27 // col为列数 28 int col = l / (2 * numRows - 2); 29 int remainder = l % (2 * numRows - 2); 30 if (remainder >= 0 && remainder <= numRows) { 31 col = 2 * col + 1; 32 } 33 if (remainder > numRows) { 34 col = 2 * col + 2; 35 } 36 37 // temp为辅助数组 38 int[] temp = new int[col]; 39 temp[0] = 1; 40 for (int i = 1; i < col; i++) { 41 temp[i] = 2 * i * (numRows - 1) - temp[i - 1]; 42 } 43 for (int i = 0; i < numRows; i++) { 44 if (i == 0) { 45 int j = 0; 46 while (2 * j * (numRows - 1) < l) { 47 res += s.charAt(2 * j * (numRows - 1)); 48 j++; 49 } 50 continue; 51 } 52 if (i == numRows - 1) { 53 int j = 0; 54 while ((2 * j + 1) * (numRows - 1) < l) { 55 res += s.charAt((2 * j + 1) * (numRows - 1)); 56 j++; 57 } 58 continue; 59 } 60 for (int k = 0; k < col; k++) { 61 if (k == 0 && i < l) { 62 res += s.charAt(i); 63 continue; 64 } 65 66 if(k%2==0){ 67 if(temp[k]+i-1<l){ 68 res += s.charAt(temp[k]+i-1); 69 continue; 70 } 71 } 72 73 if (k % 2 == 1) { 74 if (temp[k] - i + 1 < l) { 75 res += s.charAt(temp[k] - i + 1); 76 continue; 77 } 78 } 79 break; 80 } 81 82 } 83 84 return res; 85 } 86 }
思路:

另一种解法:
1 /** 2 * 时间复杂度也为O(n) 但更快 3 */ 4 public static String convert1(String s, int numRows) { 5 if(numRows==1) return s; 6 int x = 2 * (numRows-1); // distance between pipes |/|/|... 7 int len = s.length(); 8 char[] c = new char[len]; 9 int k =0; 10 for(int i=0; i < numRows; i++) 11 { 12 for(int j=i;j<len;j=j+x) 13 { 14 c[k++] = s.charAt(j); 15 if(i>0 && i<numRows-1 && j+x-2*i < len) 16 { 17 c[k++] = s.charAt(j+x-2*i); // extra character between pipes 18 } 19 } 20 } 21 return new String(c); 22 }
思路比我的更加清晰。通过加断点debug可以理解算法思想。

浙公网安备 33010602011771号