Easy solution. O(s.length * numRows) space and time complexity. Any improvement?


  • 0
    O
    public class Solution {
        public String convert(String s, int numRows) {
        	if (numRows == 1) {
        		return s;
        	}
            int x = 0, y = 0, diag = numRows - 2, i;
            int length = s.length();
            if (length < numRows) {
                return s;
            }
            int size = length/numRows + numRows;
            char[][] m = new char[numRows][length];
            char c;
            for(i = 0; i < length; i++) {
                c = s.charAt(i);
                if (y < numRows) {
                    m[y++][x] = c;
                } else if (diag > 0) {
                    m[diag--][++x] = c;
                } else {
                    m[0][++x] = c;
                    y = 1;
                    diag = numRows - 2;
                }
            }
            String res = "";
            for(y = 0; y < numRows; y++) {
                for(x = 0; x < length; x++) {
                    if (m[y][x] > 0) {
                        res += Character.toString(m[y][x]);
                    }
                }
            }
            
            return res;
        }
    }
    

Log in to reply
 

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