[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 text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

解法: 

  n = 2 时,字符串坐标变成zigzag的走法就是:

0 2 4 6

1 3 5 7

  n = 3 时,字符串坐标变成zigzag的走法就是:

0     4     8

1  3  5  7  9

2     6     10

  n = 5 时,字符串坐标变成zigzag的走法就是:

0           8             16

1        7  9         15  17

2     6     10     14     18

3  5        11  13        19

4           12            20

  可以发现,画红色的(一个循环)长度永远是 2n-2。

  利用这个规律,可以按行填字,第一行和最后一行,就是按照2n-2的顺序一点点加的。

  其他行除了上面那个填字规则,就是还要处理斜着那条线的字,可以发现那条线的字的位置永远是 j+(2n-2)-2i(i 是当前行的索引,j 是当前行的当前循环的起始值,如 i = 1 时,j 依次等于 1, 9, 17....)。

public class Solution {
    public String convert(String s, int numRows) {
        if ((s == null) || (s.length() == 0) || (numRows <= 0))
            return "";
        if (numRows == 1)
            return s;
            
        StringBuilder res = new StringBuilder("");
        int size = 2 * numRows - 2;
        for (int i = 0; i < numRows; i++) {
            for (int j = i; j < s.length(); j += size) {
                res.append(s.charAt(j));
                if ((i != 0) && (i != numRows - 1)) {
                    int temp = j + size - 2 * i;
                    if (temp < s.length()) {
                        res.append(s.charAt(temp));
                    }
                }
            }
        }
        return res.toString();
    }
}
原文地址:https://www.cnblogs.com/strugglion/p/6391157.html