Posted on

Description

Submission

class Solution {
public:
    string reverseWords(string s) {
        if(s.empty()) return "";
        if(s[0] == ' ') return reverseWords(s.substr(1, s.size() - 1));
        int i = 0;
        for(; i < s.size() && s[i] != ' '; ++i);
        string word = s.substr(0, i);
        for(; i < s.size() && s[i] == ' '; ++i);
        if(i == s.size()) return word;
        return reverseWords(s.substr(i, s.size() - i)) + " " + word;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *