LeetCode 6. ZigZag Conversion

Description

LeetCode 6. ZigZag Conversion

Example

LeetCode 6. ZigZag Conversion

Code

  • java
class Solution {
    public String convert(String s, int numRows) {
        if(numRows < 2 || s == null || s.length() == 0) return s;
        int len = s.length();
        int loop = 2*numRows-2;
        int cols = len % loop == 0 ? len / loop : len / loop + 1;
        cols *= (numRows-1);
        char[][] str = new char[numRows][cols];
        for(int i = 0; i < numRows; i++) {
            for(int j = 0; j < cols; j++) {
                str[i][j] = ' ';
            }
        }
        int i = 0, j = 0;
        int cnt = 0;
        while(cnt < len) {
            if(i == 0) {
                for(; cnt < len && i < numRows; i++) {
                    str[i][j] = s.charAt(cnt++);
                }
                i-=2;
                j++;
            } else {
                str[i][j] = s.charAt(cnt++);
                i--;
                j++;
            }
        }
        StringBuilder sb = new StringBuilder();
        for(i = 0; i < numRows; i++) {
            for(j = 0; j < cols; j++) {
                if(str[i][j] != ' ') {
                    sb.append(str[i][j]);
                }
            }
        }
        return sb.toString();
    }
}
  • Official Solution
class Solution {
    public String convert(String s, int numRows) {

        if (numRows == 1) return s;

        List<StringBuilder> rows = new ArrayList<>();
        for (int i = 0; i < Math.min(numRows, s.length()); i++)
            rows.add(new StringBuilder());

        int curRow = 0;
        boolean goingDown = false;

        for (char c : s.toCharArray()) {
            rows.get(curRow).append(c);
            if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
            curRow += goingDown ? 1 : -1;
        }

        StringBuilder ret = new StringBuilder();
        for (StringBuilder row : rows) ret.append(row);
        return ret.toString();
    }
}
  • Official Solution2
class Solution {
    public String convert(String s, int numRows) {

        if (numRows == 1) return s;

        StringBuilder ret = new StringBuilder();
        int n = s.length();
        int cycleLen = 2 * numRows - 2;

        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j + i < n; j += cycleLen) {
                ret.append(s.charAt(j + i));
                if (i != 0 && i != numRows - 1 && j + cycleLen - i < n)
                    ret.append(s.charAt(j + cycleLen - i));
            }
        }
        return ret.toString();
    }
}

Conclusion

  • 还是要仔细找规律

相关文章: