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"
不难,但是要注意时间按复杂度和“zigzag”的定义。
zigzag的含义:。应该这样排列字符
根据题意可以暴力来解,新建个二维数组来存对象,再输出。如下:
1 public static String convert(String s, int nRows) { 2 3 Character[][] zigzag = new Character[nRows][s.length()]; 4 String reslut = new String(); 5 int length = 0; 6 int slength = s.length(); 7 int j; 8 9 if (slength <= 1 || nRows == 1) { 10 return s; 11 } 12 13 for (j = 0; length < slength; j++) { 14 if (j % (nRows - 1) == 0) { 15 for (int i = 0; i < nRows && length < slength; i++) { 16 zigzag[i][j] = s.charAt(length); 17 length++; 18 } 19 } else { 20 21 zigzag[nRows - j % (nRows - 1) - 1][j] = s.charAt(length); 22 length++; 23 24 } 25 26 } 27 28 for (int i = 0; i < nRows; i++) { 29 for (int k = 0; k <= j; k++) { 30 if (zigzag[i][k] != null) { 31 32 reslut = reslut + zigzag[i][k]; 33 } 34 } 35 } 36 return reslut; 37 }
问题是会超时。
其实这个题只要找到规律直接扫描就可以了:
这确的代码:
1 public String convert(String s, int nRows) { 2 3 int length = s.length(); 4 if (length <= 1 || nRows == 1) { 5 return s; 6 } 7 8 String reslut = new String(); 9 10 int i = 0; 11 int j = 0; 12 int[] temp = new int[s.length()]; 13 while (j < length) { 14 temp[i] = j; 15 j = j + 2 * (nRows - 1); 16 i++; 17 } 18 19 int flag = 0; 20 while (flag < nRows) { 21 if (flag == 0) { 22 int k = 0; 23 while (k < i) { 24 reslut = reslut + s.charAt(temp[k]); 25 k++; 26 } 27 } else if (flag == nRows - 1) { 28 int k = 0; 29 while (k < i) { 30 if (temp[k] + nRows - 1 < length) { 31 reslut = reslut + s.charAt(temp[k] + nRows - 1); 32 } 33 k++; 34 } 35 } else { 36 int k = 0; 37 while (k < i) { 38 39 if (temp[k] + flag < length) { 40 reslut = reslut + s.charAt(temp[k] + flag); 41 } 42 43 if (temp[k] + 2 * nRows - flag - 2 < length) { 44 reslut = reslut + s.charAt(temp[k] + 2 * nRows - flag - 2); 45 } 46 47 k++; 48 } 49 } 50 flag++; 51 } 52 return reslut; 53 }