Why my Solution Gets "Time Limit Exceeded"?


  • 0
    S

    I think the solution is pretty straightforward, but still I get "Time Limit Exceeded". Can someone explain me why? Here is my solution:

    public String reverseWords(String s) {
        if(s==null || s.length() <=1)
            return s;
        String[] splits = s.split(" ");
        StringBuilder res = new StringBuilder();
        for(String str : splits){
            if(!str.isEmpty()){
                res.append(reverse(str));
                res.append(" ");   
            }    
        }
        res.deleteCharAt(res.length()-1);
        return res.toString();
    }
    
    public static String reverse(String str){
        if(str==null || str.length()<=1)
            return str;
        int start = 0;
        int end = str.length()-1;
        char[] curr = str.toCharArray();
        while(start<end){
            char temp = curr[start];
            curr[start] = curr[end];
            curr[end] = temp;
        }
        return new String(curr);
       }

Log in to reply
 

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