C++ , super-clean, in-place, 12ms, 12 lines


  • 0
    R

    C++11::

    void reverseWords(string &s) 
    {
        reverse( s.begin(), s.end());
    
        auto left = find_if( s.begin(), s.end(), [] (char c) { return c != ' ';} );   
        auto new_end = s.begin();
        string space;
        while (left != s.end())
        {
            auto right = find(left, s.end(), ' ');
            reverse(left, right);
            new_end = copy(space.begin(), space.end(), new_end);
            new_end = copy(left, right, new_end);
            left = find_if( right, s.end(), [] (char c) { return c != ' ';} );
            space = " ";
        }
         s.resize( new_end - s.begin());  
    }

Log in to reply
 

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