Here is my accepted JAVA code with simple explanation.


  • 0
    W

    Except the first and the last ZigZag line, each line has the same repeat pattern. I use tmp to mark every interval between two elements in the same line and judge if the current line is the first or the last line. Remind that 2*(numRows-1) is a formed interval between the elements of the first and the last line.

    public class Solution {
        public String convert(String s, int numRows) {
            if(numRows == 1)
            return s;
            StringBuffer res = new StringBuffer();
            int curr = 0;
            int tmp = 0;
            for(int i=0; i<numRows; i++)
            {
                curr = i;
                tmp = 2 * (numRows - i - 1);
                while(curr < s.length())
                {
                    res.append(s.charAt(curr));
                    if(tmp == 0 || tmp == 2 * numRows - 2)
                    curr += 2 * numRows - 2;
                    else
                    {
                        curr = curr + tmp;
                        tmp = 2 * numRows - 2 - tmp;
                    }
                }
            }
            return res.toString();
        }
    }
    

Log in to reply
 

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