C++ 15lines in-place 12ms


  • 1
    X
    void ReverseWords(string &s) {
        s.erase(find_if_not(s.rbegin(), s.rend(), ptr_fun<int, int>(isspace)).base(), s.begin());
    	s.erase(s.begin(), find_if_not(s.begin(), s.end(), ptr_fun<int, int>(isspace)));
    	reverse(s.begin(), s.end());
    	auto beg = s.begin(), end = s.end();
    	while(true) {
    		end = find_if(beg, s.end(), ptr_fun<int, int>(isspace));
    		reverse(beg, end);
    		beg = end;
    		if (beg == s.end())
    			break;
    		else {
    			beg ++;
    			s.erase(beg, find_if_not(beg, s.end(), ptr_fun<int, int>(isspace)));
    		}
    	}
    }

  • 0
    C

    execellent usage of STL~
    a little typo, s.begin() in line 2 should be s.end().


  • 0
    X

    which s.begin()?


  • 0
    C

    sorry, line
    "s.erase(find_if_not(s.rbegin(), s.rend(), ptr_fun<int, int>(isspace)).base(), s.begin());"
    should be
    “s.erase(find_if_not(s.rbegin(), s.rend(), ptr_fun<int, int>(isspace)).base(), s.end());”.
    the top two lines of the method is a strip operation, right? so first you remove the tailing spaces by finding the position of first no-space character from the end(aka, rbegin), then erase the part from this position to the end of the string s.


  • 0
    X

    Yes, my bad. It should be "s.erase(find_if_not(s.rbegin(), s.rend(), ptrfun<int, int>(isspace)).base(), s.end())"


Log in to reply
 

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