My short Java solution based on simple index calculations


  • 1
    M
    public String convert(String s, int nRows) {
            StringBuilder sb = new StringBuilder();
            int diff = (nRows - 1) * 2;
            
            if(diff == 0) return s;
            
            int currDiff = diff; 
            for(int i = 0; i < nRows; i++) {
                int pos = i;
                while(pos < s.length()) {
                    sb.append(s.substring(pos, pos+1));
                    pos += (currDiff == diff || currDiff == 0) ? diff : 
                           ((pos - i) % diff == currDiff ? diff - currDiff : currDiff);
                }
                currDiff -= 2;
            }
            
            return sb.toString();
    }
    

    The index is calculated based on nRows. currDiff decreases by 2 everytime and you add currDiff and diff - currDiff alternatively for each row.


Log in to reply
 

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