C++ solution O(n) space 4ms


  • 0
    A
    std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
        std::stringstream ss(s);
        std::string item;
        while (std::getline(ss, item, delim)) {
            elems.push_back(item);
        }
        return elems;
    }
    
    class Solution {
    public:
        void reverseWords(string &s) {
            vector<string> splitVec, retVec;
            split(s, ' ',  splitVec);
            s = "";
            for (int i = splitVec.size() - 1; i >= 0; --i)
            {
                if (s != "" && splitVec[i] != "")
                    s.append(" ");
                s.append(splitVec[i]);
            }
        }
    };

Log in to reply
 

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