6-lines 8ms C++ Solution

  • 4

    The idea is simple: reverse the full string s first and then reverse each word in it in place. For reversing each word, we just need to locate the left and right boundaries of the word. The code is as follows.

    class Solution { 
        void reverseWords(string &s) {
            reverse(s.begin(), s.end());
            int n = s.length(), l = 0, r = 0;
            while (r < n) {
                while (r < n && !isspace(s[r])) r++;
                reverse(s.begin() + l, s.begin() + r); 
                l = ++r;

  • 1

    You could use the standard reverse for the words as well, no need for your own function:

    reverse(s.begin() + l, s.begin() + r);

    Or if l and r were iterators:

    reverse(l, r);

  • 0

    Hi, Stefan. Thank you! I have updated my code now. It becomes more concise and without the inelegant r - 1 :-)

  • 0
    This post is deleted!

Log in to reply

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