Simple Java solution


  • 0
    Z
    class Solution {
        public String convert(String s, int numRows) {
            int len = s.length();
            if (len == 0 || numRows <= 1) return s;
            int c = len / (numRows + numRows - 2);
            int rem = len % (numRows + numRows - 2);
            int numCols = c * (1 + numRows - 2);
            if (rem > numRows) numCols += rem - numRows + 1; // get num of cols first
            else if (rem > 0) numCols += 1;
            char[][] chs = new char[numRows][numCols];
            for (int i = 0; i < numRows; i++) { // duplicate an empty arrays
                Arrays.fill(chs[i], ' ');
            }
            int i = 0, j = 0, k = 0;
            while (k < s.length()) { // zigzag conversion
                while (i < numRows && k < s.length()) {
                    chs[i][j] = s.charAt(k);
                    i++;k++;
                }
                i -= 2;j++;
                while (i > 0 && k < s.length()) {
                    chs[i][j] = s.charAt(k);
                    i--;j++;k++;
                }
            }
            StringBuilder sb = new StringBuilder();
            for (i = 0; i < numRows; i++) { // read out the character
                for (j = 0; j < numCols; j++) {
                    if (chs[i][j] != ' ') {
                        sb.append(chs[i][j]);
                    }
                }
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.