C++ answer to the question


  • 0
    I

    This question is seemingly easy but at least for me, it was tricky to get it right. My approach is that I trim white space front and back first and reverse words one at a time. if we find extra white space, move the pointer and erase extra white space.

    void reverseWords(string &s) {
        if (s.size() == 0) return;
        // trim white space in the beginning
        while (s.size() != 0 && s[0] == ' ') s.erase(0, 1);
        
        reverse(s.begin(), s.end());
        
        // trim white space in the begininng - this was at the end earlier
        while (s.size() != 0 && s[0] == ' ') s.erase(0, 1);
        if (s.size() <= 1) return;
        int start = 0;
        while (1)
        {
            size_t whtspace = s.find(" ", start);
            if (whtspace != string::npos) {
                reverse(s.begin()+start, s.begin()+whtspace);
            } else if (whtspace == string::npos) {
                // last word
                reverse(s.begin()+start, s.end());
                break;
            }
            start = whtspace;
            // do we have extra white space?
            while (s.size() > start && s[start] == ' ') start++;
            if (start-whtspace > 1) {
                s.erase(whtspace, start-whtspace-1);
                start = whtspace + 1;
            }
        }
    }

Log in to reply
 

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