Reverse each word within a string

  • 0

    Question : Reverse each word within a string


    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--){
            String[] words=revofs.split("\\s");
            for(int i=words.length-1; i>=0;i--){
                if (i==words.length-1)
                    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.