How is this so slow?


  • 0
    C

    Only beats 17% . I would appreciate your feedback on how to make it faster. Thanks.

    public class Solution {
        public String convert(String s, int numRows) {
            String result = "";
            if (numRows == 1) {
                result = s;
            } else {
                ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>();
                for (int i = 0; i < numRows; i++) {
                    rows.add(new ArrayList<String>());
                }
                int sorter = 0;
                boolean dirDown = true;
                for(int j = 0; j < s.length(); j++) {
                    rows.get(sorter).add(String.valueOf(s.charAt(j)));
                    if (sorter == numRows - 1) {
                        dirDown = false;
                    } else if (sorter == 0){
                        dirDown = true;
                    }
                    
                    if (dirDown) {
                        sorter++;
                    } else {
                        sorter--;
                    }
                }
                for(ArrayList<String> letterlist: rows) {
                    for(String letter: letterlist) {
                        result = result + letter;
                    }
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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