LeetCode 6.

Tags:

Complexity

  • Time complexity: O(n)

  • Space complexity: O(n)

Code

class Solution {
    public String convert(String s, int numRows) {
        if (numRows == 1) return s;

        String[] rows = new String[numRows];
        Arrays.fill(rows, "");
        int row = 0;
        boolean inc = true; 
        for (int i=0; i<s.length(); i++) {
            rows[row] += s.charAt(i);
            if (inc && ++row == numRows) {
                inc = false;
                row -= 2;
            }else if (!inc && --row < 0){
                inc = true;
                row = 1;
            }
        }

        StringBuffer result = new StringBuffer();
        for (int i=0; i<numRows; i++) {
            result.append(rows[i]);
        }
        return result.toString();
    }
}

Check out the description of this problem at LC 6.