6. ZigZag Conversion

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".

方法:构造String数组[row] 按zigzag型copy from input_str

思路:构造String数组ret[numRows]分别来保存reformated后的每行字符。
依次遍历字符串s,将字符交替以两种位置次序{正向ret[0 -> row-1},逆向ret[row-1 -> 1]} 放到ret[numRows]数组中,连接ret[numRows]数组后返回结果。

Time Complexity: O(s.length)
Space Complexity: O(s.length)

Example:

Given "0123456789ABCD..", and numRows=4
0   6   C
1 5 7 B D
2 4 8 A .
3   9   .

Code:

public class Solution {
    public String convert(String s, int numRows) {
        
        // init result strings for different rows
        StringBuffer[] ret_str = new StringBuffer[numRows];
        for (int i = 0; i < ret_str.length; i++)
            ret_str[i] = new StringBuffer();

        // copy according to the format required
        int i = 0; //index for input string s
        while (i < s.length()) {
            for (int row = 0; row < numRows && i < s.length(); row++) { //down
                ret_str[row].append(s.charAt(i++));
            }
            for (int row = numRows - 2; row > 0 && i < s.length(); row--) { //up
                ret_str[row].append(s.charAt(i++));
            }
        }

        // prepare the result
        for (int row = 1; row < ret_str.length; row++) {
            ret_str[0].append(ret_str[row]);
        }
        return ret_str[0].toString();
    }
}

你可能感兴趣的:(6. ZigZag Conversion)