My one-pass solution in Java

  • 0

    It is time-complexity O(n+l) and space -complexity O(n)

    public class Solution {
    public  String convert(String s, int nRows) {
        if (s==null||s.length()==0||nRows<=1) return s;
        String[] array= new String[nRows];
        for (int i=0;i<nRows;i++)
        for (int i=0;i<s.length();i++){
            int position = i%(2*nRows-2);
            if (position<nRows)
                array[position]=new StringBuilder(array[position]).append(s.charAt(i)).toString();
                array[2*nRows-2-position]=new StringBuilder(array[2*nRows-2-position]).append(s.charAt(i)).toString();
        for (int i=1;i<nRows;i++)
            array[0]= new StringBuilder(array[0]).append(array[i]).toString();
        return array[0];


  • 0

    If anyone needs explanation, I will add some comments. It looks quite straightforward.

  • 0

    I don't think it's one pass. Because you must combine the nRows string to a string, I think this is another pass, so maybe the title change to two pass will be more available?

Log in to reply

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