Sharing a pretty easy java solution

  • 5
    public String convert(String s, int numRows) {
            StringBuilder res = new StringBuilder();
            StringBuilder[] sb = new StringBuilder[numRows];
            for(int i=0;i<sb.length;i++)    sb[i] = new StringBuilder();
            int i=0;
                for(int n=0;n<numRows&&i<s.length();n++) sb[n].append(s.charAt(i++));
                for(int n=0;n<numRows-2&&i<s.length();n++)    sb[numRows-2-n].append(s.charAt(i++));
            for(StringBuilder b: sb)    res.append(b);
            return res.toString();

    Unlike normal solution with i+=(numRows-i)*2-2 through line by line foreach i in numRows-1, but also with the last need to be the same gap as first line, this solution traverse as the order of input, and create a StringBuilder array for it.

Log in to reply

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