Simple in place c++ solution


  • 0
    D

    Remove spaces. Reverse sentence and then reverse each word

    class Solution {
    public:
        void reverseW(string& s, int from, int to)
        {
            for(int i=from; i<(to-from)/2+from; ++i){
                swap(s[i], s[to-1-i+from]);
            }
        }
        void reverseWords(string &s) {
            //clear spaces
            for(int i=0; i < s.size(); ++i){
                if(s[i] == ' '){
                    size_t pos = s.find_first_not_of(' ', i);
                    s.erase(i, pos-(i?1:0)-i);
                }
            }
            //reverse sentence
            reverseW(s, 0, s.size());
            //reverse each word
            for(size_t i=0; i<s.size(); ++i){
                size_t pos = s.find(' ', i);
                pos = pos==string::npos?s.size():pos;
                reverseW(s, i, pos);
                i = pos;
            }
        }
    };

  • 0
    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)));
    		}
    	}
    }
    

    15 lines, using stl


Log in to reply
 

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