Easy to understand implementation in java


  • 0
    P
     public String convert(String s, int numRows) {
        //for these inputs there is no change in output
        if(s.length()<3 || numRows==1)
            return s;
        char[] chars = s.toCharArray();
        StringBuilder builder = new StringBuilder();
        
        //there are two gaps one going like left-gap: |/ and other going like this right-gap: /|
        int rgap = 0; //top element
        int lgap = numRows * 2 - 2; //this is |/ is 2x the numrows but the bottom element is common
                                    //and index is one less.    
        
        for (int i = 0; i < numRows; i++) {
            int j = i;
            while (j < chars.length) {
                if (j == i) 
                    builder.append(chars[j]); //print first char
                if (lgap != 0 && j + lgap <= chars.length - 1)
                    builder.append(chars[j + lgap]); //print char after first gap
                if (rgap != 0 && j + lgap + rgap <= chars.length - 1)
                    builder.append(chars[j + lgap + rgap]); //print char after second gap
                j = j + lgap + rgap;
    
    
            }
            lgap = lgap - 2; //both gap reduce by 2 chars
            rgap = rgap + 2;
        }
        return builder.toString();
    }

Log in to reply
 

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