Share My Straightforward Solution


  • 1
    A

    The idea is to create nRows strings, each time I select to append the string in zigzag order, i.e. fill 1st, 2nd, 3rd, 2nd, 1st, 2nd, 3rd, ....

             public String convert(String s, int nRows) {
                if (nRows == 1) {
                    return s;
                }
                StringBuffer[] strBuffer = new StringBuffer[nRows];
                for (int i=0; i<strBuffer.length; i++) {
                    strBuffer[i] = new StringBuffer();
                }
                
                boolean increase = false;
                for (int i=0, ptr=0 ; ptr < s.length(); ptr++) {
                    strBuffer[i].append(s.charAt(ptr));
                    if (i==0 || i== nRows-1) increase = !increase;
                    if (increase) {
                        i++;
                    } else {
                        i--;
                    }
                }
                StringBuffer result = new StringBuffer();
                for (int i=0; i<strBuffer.length; i++)
                    result.append(strBuffer[i].toString());
                return result.toString();
            }

Log in to reply
 

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