8ms Java Solution based on ZigZag pattern (level by level traversal)


  • 0

    The pattern is like this, take rows=4, the first row and last row will have one step of 6 ( 6 is the max step here, computed by 2*(4-1) ), then in between the rows, there are two segments, each with firstStep ( 6-2i) and secondStep (2i), where i is the row index.

    public String convert(String s, int numRows) {
        if(numRows==1)
            return s;
        int dis = 2*(numRows-1);
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<numRows; i++) {
            if(i==0 || i==numRows-1) {
                int j = i;
                while(j<s.length()) {
                    sb.append(s.charAt(j));
                    j += dis;
                }
            } else {
                int secondStep = i*2;
                int firstStep = dis - i*2;
                int j = i;
                int step = firstStep;
                while(j<s.length()) {
                    sb.append(s.charAt(j));
                    j += step;
                    step = step==firstStep ? secondStep : firstStep; // alertnate step size
                }
            }
        }
        return sb.toString();
    }

Log in to reply
 

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