leetcode6---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".
题目分析:返回一个字符串的类似于"Z"字形走法,没有想到什么别的方法。模拟步骤走一遍就能得出结果。

    public String convert(String s, int numRows) {
        if (s == null)
            return null;
        if (s.length() <= 1)
            return s;
        StringBuffer[] sbs = new StringBuffer[numRows];
        for (int i = 0; i < sbs.length; i++) {
            sbs[i] = new StringBuffer();
        }
        int j = 0;
        while (j < s.length()) {
            for (int i = 0; i < numRows; i++) {
                if (j < s.length()) {
                    char c = s.charAt(j++);
                    sbs[i].append(c);
                } else {
                    break;
                }
            }

            for (int l = numRows - 2; l > 0; l--) {
                if (j < s.length()) {
                    char c = s.charAt(j++);
                    sbs[l].append(c);
                } else {
                    break;
                }
            }
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < numRows; i++) {
            sb.append(sbs[i]);
        }
        return sb.toString();
    }

你可能感兴趣的:(leetcode6---ZigZag Conversion)