LeetCode ---6.ZigZag Conversion

 1 public String convert(String s, int numRows) {
 2         if(numRows == 1)    return s;
 3         StringBuilder str = new StringBuilder("");
 4         char[] ch = s.toCharArray();
 5         int block_m = 0;
 6         int block_n = 0;
 7         int i = 0, j = 0;
 8         char[][] store = new char[numRows][(numRows - 1) * (ch.length / (2 * numRows - 2) + 1)];
 9         for(int index = 0; index < ch.length; index ++) {
10             block_m = index / (2 * numRows - 2);
11             block_n = index % (2 * numRows - 2);
12             if(block_n / numRows == 0) {
13                 i = block_n % numRows;
14                 j = block_m * (numRows - 1);
15             } else {
16                 i = numRows - block_n % numRows -2;
17                 j = block_m * (numRows - 1) + block_n % numRows +1;
18             }
19             char a = ch[index];
20             store[i][j] = a;
21         }
22         for(i = 0; i < numRows; i ++) {
23             for(j = 0; j < store[0].length; j ++) {
24                 if(store[i][j] == '\u0000')
25                     continue;
26                 str = str.append(store[i][j]);
27                 
28             }
29         }
30         return str.toString();
31     }

 更直接简便的解法:

Z字形排列之后,每一行元素在原字符串中的位置就是一组(首尾两行)或两组(中间)等差数列

 1 public String convert(String s, int numRows) {
 2         if(numRows == 1)    return s;
 3         char[] ch = s.toCharArray();
 4         char[] store = new char[ch.length];
 5         int index = 0;
 6         for(int i = 0; i < numRows; i ++) {
 7             for(int j = 0; i + (2 * numRows - 2) * j < ch.length; j ++) {
 8                 store[index++] = ch[i + (2 * numRows - 2) * j];
 9                 if(i != 0 && i != numRows - 1 && 2 * numRows - 2 - i + (2 * numRows - 2) * j < ch.length) {
10                     store[index++] = ch[2 * numRows - 2 - i + (2 * numRows - 2) * j];
11                 }
12             }
13         }
14         return new String(store);
15     }

 

posted @ 2017-05-15 21:09  zouxiaochuan  阅读(127)  评论(0)    收藏  举报