My simple java solution

  • 7
    public class Solution {
        public String convert(String s, int nRows) {
            if(nRows <=1)
                return s;
           StringBuilder[] r = new StringBuilder[nRows];
           for( int i=0; i<nRows; i++ )
               r[i] = new StringBuilder();
            int base = nRows+nRows-2;
            char[] toks = s.toCharArray();
            for(int i = 0; i < toks.length; i++)
                int t = i % base;
                if(t < nRows)
            for( int i = 1; i<nRows; i++ )
                r[0].append( r[i] );
            return r[0].toString();

  • 0

    why when I input ABC , 2 expected output is ACB , I think the output should be ABC , who can tell me ? why?

    I got it , thanks for nelson3's reply!

  • 0

    Your input is:
    when you read each line, is ACB

  • 0

    Just realize that the format if off....

    You have 2 rows, so the zigzag pattern will be
    A(0, 0) C(0, 1)
    B(1, 0).
    If you consider the zigzag format as in a matrix form, the digits in the parentheses show the row and column number of the characters in that matrix . Then if you read them line by line (row by row), the result will be ACB.

    Another example is ABCDEFGHIJKL, 4. Now you have 4 rows, the zipzag format of the string will be
    A(0,0) G (0,3)
    B(1, 0) F(1,2) H (1, 3) L (1,5)
    C(2,0) E(2,1) I (2, 3) K (2, 4)
    D(3,0) J (3, 3)
    and the line-by-line output will be AGBFHLCEIKDJ.

  • 0

    I assume ABC in two rows representation should be:
    A C
    [second row] B

  • 0

    I have the same question with yours. Could you tell me something about it? Why excepted is ACB and output is ACB is wrong.

Log in to reply

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