leetCode 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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I
1 // 方法一超过38.49% 2 public String convert(String s, int numRows) { 3 if (numRows <= 1 || s.length() <= 1) return s; 4 char[][] res = new char[numRows][s.length() * (numRows - 1) / (2 * numRows - 2)+1]; 5 boolean direction = true;//行走方向,默认是向下走 6 int row = 0, col = 0;//下一个填的位置 7 for (int i = 0; i < s.length(); i++) { 8 res[row][col] = s.charAt(i); 9 if (row == numRows - 1) {//触底,改变行走方向 10 direction = false; 11 } 12 if (i != 0 && row == 0) {//碰头,改变行走方向 13 direction = true; 14 } 15 if (direction) {// 向下走 16 ++row; 17 } else {// 向右上走 18 --row; 19 ++col; 20 } 21 } 22 s=new String(""); 23 for (int i = 0; i < res.length; i++) { 24 for (int j = 0; j < res[0].length; j++) { 25 if (res[i][j] != '\0') 26 s += res[i][j]; 27 } 28 } 29 return s; 30 } 31 32 // 方法二:超过30.42% 33 String strOfi(String s, int begin, int step) { 34 String rs = new String(""); 35 36 while (begin < s.length()) { 37 rs += s.charAt(begin); 38 begin += step; 39 } 40 return rs; 41 } 42 public String convert(String s, int numRows) { 43 if (numRows <= 1) return s; 44 String rs = new String(""); 45 //第一行 46 rs += strOfi(s, 0, 2 * numRows - 2); 47 //中间行 48 for (int i = 1; i < numRows-1; i++) { 49 String s1 = new String(""); 50 String s2 = new String(""); 51 s1=strOfi(s,i,2*numRows-2); 52 s2=strOfi(s,2*numRows-i-2,2*numRows-2); 53 54 int j,k; 55 for (j = 0,k=0; j < s1.length() && k<s2.length(); j++,k++) { 56 rs+=s1.charAt(j); 57 rs+=s2.charAt(k); 58 } 59 if (j < s1.length()){ 60 rs+=s1.charAt(j); 61 } 62 if (k<s2.length()){ 63 rs+=s2.charAt(k); 64 } 65 } 66 //最后一行 67 rs += strOfi(s, numRows - 1, 2 * numRows - 2); 68 return rs; 69 }