Java Zig Zag solution


  • 0
    D
    class Solution {
        public String convert(String s, int numRows) {
    
    		if (s == null || "".equals(s)) return "";
    
    		if (numRows == 0 || numRows == 1) return s;
    
    		StringBuilder[] sbs = new StringBuilder[numRows];
    		for (int i = 0; i < numRows; i++) {
    			sbs[i] = new StringBuilder();
    		}
    
    		char[] chs = s.toCharArray();
    		int len = chs.length;
    		int i = 0;
    		while (i < len) {
    			int index;
    			for (index = 0; index < numRows && i < len; index++) {
    				sbs[index].append(chs[i++]);
    			}
    			for (index = index - 2; index >= 1 && i < len; index--) {
    				sbs[index].append(chs[i++]);
    			}
    		}
    
    		StringBuilder sb = new StringBuilder();
    		for (StringBuilder line : sbs) {
    			sb.append(line.toString());
    		}
    		return sb.toString();
    	}
    }
    

Log in to reply
 

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