[C++] in-place easy to understand solution


  • 0
    K
    class Solution {
    public:
        string reverseWords(string s) {
            for(int word_start = 0, word_end = 0; word_start < s.size(), word_end < s.size();)
            {
                while (word_end < s.size() && s[word_end] != ' ')
                    ++word_end;
                    
                for (int i = word_start, j = word_end - 1; i < j; i++, j--)
                    std::swap(s[i], s[j]);
                    
                word_start = ++word_end;
            }
            
            return s;
        }
    };
    

Log in to reply
 

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