One StringBuilder, O(n) Java solution, using output formula


  • 0
    M
     public String convert(String s, int nRows) {
        if(s == null) return null;
        if(s.length() == 0 || nRows <= 1) return s;
        
    	StringBuilder builder = new StringBuilder();
    	for (int i = 0; i < nRows; i++) {
    		int index = i;
    		while(index < s.length()){
    			builder.append(s.charAt(index));
    			int n = index + 2 * (nRows - i - 1);
    			if(i > 0 && i < nRows - 1 && n < s.length()){
    				builder.append(s.charAt(n));
    			}
    			index += (nRows - 1) * 2;
    		}
    	}
    	return builder.toString();
    }

Log in to reply
 

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