C++ solution in-place O(1)


  • 0
    M
    class Solution {
    public:
        void reverseWords(string &s) {
            int j=s.size()-1;
            while(1){
                if(j == -1)
                    break;
                if(s[j] == ' '){
                    s.pop_back();
                    j--;
                }
                else
                    break;
            }
            reverse(s.begin(), s.end());
            int sign = 0;
            int i = s.size()-1;
            while(1){
                if(i == -1)
                    break;
                if(s[i] == ' '){
                    s.pop_back();
                    i--;
                }
                else
                    break;
            }
            i = 0;
            for(;i<s.size();i++){
                if(s[i] == ' ' && s[i+1] != ' '){
                    reverse(s.begin()+sign, s.begin()+i);
                    sign = i+1;
                }
                else if(s[i] == ' ' && s[i+1] == ' '){
                    s.erase(s.begin()+i);
                    i--;
                }
                else
                    continue;
            }
            reverse(s.begin()+sign, s.end());
        }
    };

Log in to reply
 

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