How to get rid of "null" in the result


  • 0
    B

    I try to solve the problem as below:

    public class Solution {
        public String convert(String s, int numRows) {
            if (numRows <= 1)
                return s;
                
            String[] zigzag = new String[numRows];
            int i = 0;
            
            for (i=0; i < numRows; i++)
            {
                zigzag[i] = "";
            }
            
            
            int rowIndex = 0;
            int direction = -1;
            while (i < s.length())
            {
                zigzag[rowIndex]+=Character.toString(s.charAt(i++));
                if (rowIndex == (numRows-1) || rowIndex == 0 )
                {
                    direction = -direction;
                }
                rowIndex +=direction;
            }
            String retS = new String("");
            for (i=0; i < numRows; i++)
            {
                retS+= zigzag[i];
            }
            return reS;
        }
    }
    

    The code has the problem that returned result has null inside it.
    E.g.: input "PAYPALISHIRING", 3,
    result is : "nullPAHNnullAPLSIIGnullYIR"
    expect is : "PAHNAPLSIIGYIR"

    I can see the sequence is correct but mixed with "null", which should come from the string array zigzag. But how should I remove these "null"?

    Thanks in advance.


Log in to reply
 

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