Java Solution - O(N)


  • 0
    J

    Since we only care about the row we are inserting into the StringBuilder(), we can use a incRow variable to determine whether to increment or decrement the row count. At the end, create a new StringBuilder to return all strings.

    class Solution {
        public String convert(String s, int numRows) {
            int row = 0; 
            Boolean incRow = true;          //Increase or decrease row count
            if (numRows <= 1)
                return s;
            ArrayList<StringBuilder> list = new ArrayList<StringBuilder>();
            for (int i = 0; i < numRows; i++){
                list.add(new StringBuilder());
            }
            for (int i = 0; i < s.length(); i++ ){
                StringBuilder str = list.get(row);
                str.append(s.charAt(i));
                
                //Increment row
                if (incRow){
                    if (row < numRows -1) row++;
                    else {
                        incRow = false;
                        row--;
                    }
                }
                //Decrement row
                else{
                    if (row == 0){
                        incRow = true;
                        row++;
                    }
                    else
                        row--;
                }
            }
            StringBuilder newStr = new StringBuilder();
            for (int i = 0; i < list.size(); i++)
                //System.out.println(list.get(i).toString());
                newStr.append(list.get(i).toString());
            return newStr.toString();
        }
    }
    

Log in to reply
 

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