题目描述
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"
.
我的解答
1 import java.lang.reflect.Array; 2 3 /** 4 * Created by Tutotu on 2016/12/6. 5 * <p> 6 * Realname:yangmingzhu 7 * <p> 8 * Tel:18511400217 9 * <p> 10 * Email:yangmingzhu921025@hotmail.com 11 */ 12 13 public class Solution2 { 14 public String convert(String s, int numRows) { 15 String result=""; 16 int index = 0; 17 int row = numRows; 18 int cow = 0; 19 char[] c = s.toCharArray(); 20 21 //if判断用于确定二位数组的列数,这里判断过于复杂,还没想到好的解决办法 22 if(numRows <= 0){ 23 System.exit(-1); 24 }else if(numRows == 1){ 25 return s; 26 }else { 27 if (s.length() > (2*numRows-2)){ 28 int l = s.length()/(2*numRows-2); 29 int m = s.length()%(2*numRows-2); 30 if (m == 0){ 31 cow = 2*l; 32 }else if (m>0 && m<=numRows){ 33 cow = 2*l + 1; 34 }else{ 35 cow = 2*l+2; 36 } 37 }else{ 38 cow = 2; 39 } 40 } 41 Character[][] temp = new Character[row][cow]; 42 //将字符数组以s型路线装入二维数组中 43 for(int i=0; i<cow; i++){ 44 if (i%2 > 0) { 45 for (int j = row-2; j > 0; j--) { 46 try { 47 temp[j][i] = c[index]; 48 index ++; 49 }catch(ArrayIndexOutOfBoundsException e){ 50 break; 51 } 52 } 53 }else{ 54 for(int j=0; j<row; j++){ 55 try { 56 temp[j][i] = c[index]; 57 index ++; 58 }catch(ArrayIndexOutOfBoundsException e){ 59 break; 60 } 61 } 62 } 63 64 } 65 66 //将二维数组中的非空字符读出,组成字符串 67 for (int i=0; i< row; i++){ 68 for (int j=0; j<cow; j++){ 69 70 if (temp[i][j] != null){ 71 //System.out.println(i+" " +j + ":" + temp[i][j]); 72 result =result+(temp[i][j].toString()); 73 } 74 } 75 } 76 return result; 77 } 78 79 80 public static void main(String[] args){ 81 Solution2 s = new Solution2(); 82 String result = s.convert("PAYPALISHIRING",5); 83 System.out.println(result); 84 } 85 }
总结
这是LeetCode上难度值为容易的一道题,还连续A了好多次,前一天晚上没A出来,晚上回去走在路上想出来办法,第二天早上又过来A出来的。
该题拿题之后,简单思考下第一想法是把字符串按顺序填入一个二维数据(矩阵),然后再做判断读取矩阵中的字符。在想用其他方法,想了半天也没思路,只能先实现第一想法。
这道题A不出来的主要难度实在对于二维数组列数的确定,刚开始总是少一列。现在写的方法中该部分也不是很好,判断过多,还有嵌套判断。任需改进。