7ms Java Solution


  • 0
    T
            StringBuilder sb = new StringBuilder(s.length());
            int totalGap = (numRows-1)*2;
            if(numRows == 1) return s;
            for(int i = 1; i<=numRows&&i<=s.length(); i++){
                sb.append(s.charAt(i-1));
                int subGap = (numRows-i)*2;
                if(subGap==totalGap||subGap==0){
                    int offset = i-1;
                    while(true){
                        if(offset+totalGap>=s.length()) break;
                        else sb.append(s.charAt(offset+totalGap));
                        offset+=totalGap;
                    }
                }
                else{
                    int offset = i-1;
                    while(true){
                        if(offset+subGap>=s.length()) break;
                        else sb.append(s.charAt(offset+subGap));
                        if(offset+totalGap>=s.length()) break;
                        else sb.append(s.charAt(offset+totalGap));
                        offset+=totalGap;
                    }
                }
            }
            return sb.toString();
    

    I calculated distance between left and right lines in zigzag, which is (numRows-1)*2. And the elements between two lines is (numsRows-i)*2 to their nearest left lines. Then use this equation to find right element to append to the stringbuilder.


  • 0
    K

    clean version :p

    public class Solution {
        public String convert(String s, int numRows) {
            StringBuilder sb = new StringBuilder();
            if(numRows == 1) {
                return s;
            }
            int zigLen = 2 * numRows - 2;
            for(int r = 0; r < numRows; r++) {
                int idx = r;
                while(idx < s.length()) {
                    sb.append(s.charAt(idx));
                    int dIdx = idx + zigLen - 2*r;
                    if(r!=0 && r!= numRows -1 && dIdx < s.length()) {
                        sb.append(s.charAt(dIdx));
                    }
                    idx += zigLen;
                }
            }
            return sb.toString();
        }
    }
    

  • 0
    T

    @zheng93 Thanks!


Log in to reply
 

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