My solution using only 1 for loop O(n)


  • 0
    A
    string reverseWords(string s) 
    {
        std::string temp="", res="";
        
        for(int i=0; i<s.length(); i++)
            if(s[i] == ' ') //append to final res
            {
                res = res + temp + " ";
                temp = "";
            }
            else //keep reversing the word
                temp = s[i] + temp;
        
        return res + temp;
    }

Log in to reply
 

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