Simple Java solution. Accepted.


  • 0
    P

    Get character from straight i-column (zig) for the row. Get cgaracter from tilt i-column (zag) for the row. Continue if there are characters left.

    public String convert(String s, int nRows) {
    	if (nRows == 1 || nRows == s.length()) return s;
        char[] chars = s.toCharArray();
        StringBuilder result = new StringBuilder();
        
        for (int r=0; r<nRows; r++) {
        	int i = 0;
        	while (true) {
        		int zig = r+i*(nRows*2-2);
        		if (zig > chars.length-1) break;
        		result.append(chars[zig]);
        		if (r > 0 && r<nRows-1) {
        			int zag = zig + (nRows-r-1)*2;
        			if (zag < chars.length) {
        				result.append(chars[zag]);
        			}
        		}
        		i++;
        	}
        }
        
        return result.toString();
    }

Log in to reply
 

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