I got "Time Limit Exceeded" when put trim() in different position


  • 1
    L

    Two solutions are not very different. One use trim them split and another one split first and trim the reversed. First solution get accepted but the second get time limit exceeded. Anybody knows why?

    public class Solution {
        public String reverseWords(String s) {
            String rs = "";
            String[] words =s.split(" ");
            for(int i=words.length; i> 0; i--){
                if(!words[i-1].isEmpty()){
                    rs = rs+words[i-1]+" ";
                }
            }
            return rs.trim();
        }
    }
    
    public class Solution {
        public String reverseWords(String s) {
            String s1 = s.trim();
            String rs = "";
            String[] words =s1.split(" ");
            for(int i=words.length; i> 0; i--){
                if(!words[i-1].isEmpty()){
                    if(!rs.isEmpty()){
                        rs = rs + " ";
                    }
                    rs = rs+words[i-1];
                }
            }
            return rs;
        }
    }

  • 0
    F

    I think the TLE Exception is because the + operation of String.
    For the first Solution: if you change the code into:

    for(int i=words.length; i> 0; i--){
            if(!words[i-1].isEmpty()){
                rs = rs+words[i-1]+" ";
                if(i>0){       //useless, just for like solution2, and find the problem
                      rs = rs + " ";
                }
            }
    } 
    

    It will be TLE too.
    I recommend you to use the StringBuilder's append method.
    BTW, it seems there is something wrong in Solution2,when add the space into the result string.


Log in to reply
 

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