C++ Solution using two pointer


  • 0
    B
    
    class Solution {
    public:
        std::string reverseWords(std::string s) {
            if (s.size() <= 1)
                return s;
            std::string::iterator iter_word_beg = s.begin();
            std::string::iterator iter_word_end = s.begin();
            while (iter_word_beg < s.end()) {
                if (*iter_word_beg == ' ') {
                    iter_word_beg++;
                    iter_word_end++;
                }
                if (*iter_word_end != ' ' && ++iter_word_end < s.end()) {
                    continue;
                }
                std::reverse(iter_word_beg,iter_word_end);
                iter_word_beg = iter_word_end;
            }
            return s;
        } 
    };

Log in to reply
 

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