Compact Java solution with no extra space

  • 0

    The idea here is to fill the solution string by skipping through the input using the correct step value for each row

    • First and last rows increment by (2*numRows - 2)
    • Any i-th row increments by (2*numRows - 2*i) then (2*i - 2)

    Here I tried to compact my code to use just 1 generalized step function (that looks pretty complicated atm)

    Any ideas on how to simplify this?

    public String convert(String s, int numRows) {
            if(numRows == 1) return s;
            StringBuilder result = new StringBuilder();
            for(int i=1; i<=numRows; i++){
                int j=i-1;
                int k=0;
                    j += k++%2==0||i==1||i==numRows?2*numRows-2*(i<numRows?i:1):2*i-2;
            return result.toString();

Log in to reply

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