Zigzag Conversion(Java)T: O(n)


  • 0
    public String convert(String s, int numRows) {
    	if(numRows == 1) {
    		return s;
    	}
    	char[] chArr = new char[s.length()];
    	int n = 2 * numRows - 2;
    	int index = 0;
    	for(int r = 1; r <= numRows; r++) {
    		for(int group = 0; (r + n * group) <= s.length(); group++) {
    			chArr[index] = s.charAt(r + n * group - 1);
    			index++;
    			if(r != 1 && r != numRows && (2 * numRows - r + n * group) <= s.length()) {
    				chArr[index] = s.charAt(2 * numRows - r + n * group - 1);
    				index++;
    			}
    		}
    	}
    	return new String(chArr);
    }

Log in to reply
 

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