Reverse each word within a string


  • 0
    L

    Question : Reverse each word within a string

    Code:

    class Solution {
        public String reverseWords(String s) {
            
            //
            String revofs= new String();
            String output= new String();
            if(s.equals("") || s.equals(" ") || s.equals(null))
                return "";
            for(int i=s.length()-1; i>=0;i--){
                revofs+=s.charAt(i);
                
            }
            String[] words=revofs.split("\\s");
            for(int i=words.length-1; i>=0;i--){
                if (i==words.length-1)
                    output+=words[i];
                else
                    output+=" " + words[i];
                
            }
            return output;
            
            
        }
    }
    
    The above code is O(n) and the solution of the editors is also O(n). But I get the error that the time limit is exceeded. Any idea as to why this is happening?

Log in to reply
 

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