C++ Solution. Beats 79.11%


  • 0
    M
    class Solution {
    public:
        string reverseWords(string s) {
            int prev = 0;
            for(int i = 0; i < s.length() ; i++)
            {   
                if(s.at(i)==' ' )
                {
                    string x = s.substr(prev,i - prev);
                    string rev(x.rbegin(),x.rend());
                    s.replace(prev,i-prev,rev);
                    prev=i+1;
                }
            }
            string x = s.substr(prev,s.length() - prev);
            string rev(x.rbegin(),x.rend());
            s.replace(prev,s.length()-prev,rev);
            
            return s;
        }
    };
    

    If you have comments, I'd like to hear.


Log in to reply
 

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