C++ solution using find, substr, reverse & erase


  • 0
    P
    class Solution {
    public:
        string reverseWords(string s) {
            std::string delimeter = " ";
            size_t pos = 0;
            std::string token;
            std::string res;
            
            while((pos = s.find(delimeter))!=std::string::npos){
                token = s.substr(0,pos+1);
                std::reverse(token.begin(), token.end()-1);
                res += token;
                s.erase(0,pos+delimeter.length());
            }
            std::reverse(s.begin(), s.end());
            return res + s;
        }
    };
    

Log in to reply
 

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