Java simple solution


  • 0
    A
        public String convert(String s, int numRows) {
        
        if (numRows <= 1) return s;
        
        StringBuilder[] rows = new StringBuilder[numRows];
        
        boolean reverse = false;
        int i = 0, j = 0;
        
        while (i < s.length()) {
            
            // append
            if (rows[j] == null) rows[j] = new StringBuilder(String.valueOf(s.charAt(i++)));
            else rows[j].append(s.charAt(i++));
            
            // switch row
            if (reverse) j--;
            else j++;
            
            // adjust if necessary
            if (j == numRows) {
                reverse = true;
                j -= 2;
            } else if (j == -1) {
                reverse = false;
                j = 1;
            }
            
        }
        
        StringBuilder builder = new StringBuilder();
        for (StringBuilder str : rows) if (str != null) builder.append(str.toString());
        return builder.toString();
    }

Log in to reply
 

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