C++ solution 8ms


  • 0
    A
    class Solution {
    public:
        void reverseWords(string &s) {
            
            // reverse sentence
            for (size_t i = 0, j = s.size()-1; i < s.size()/2; ++i,--j) 
                swap(s[i],s[j]);
            
            //reverse all words except last word
            size_t start_index = 0;
            size_t space_index = 0;
            
            // advance till first non space character;
            while(start_index < s.size() && s[start_index] == ' ') start_index++;
            if (start_index == s.size()) return;
            
            while((space_index = s.find(' ', start_index)) != string::npos) {
                for (int i = start_index, j = space_index-1; i <= j; ++i, --j)
                    swap(s[i], s[j]);
                
                // advance till next space
                while (space_index < s.size() && s[space_index] == ' ') space_index++;
                if (space_index == s.size()) break;
                start_index = space_index;
                
            }
            
            if (start_index == s.size()) return; // end of string
            
            // reverse last word
            for (int i = start_index, j = s.size()-1; i <= j; ++i, --j) 
                swap(s[i], s[j]);
            
            return;
            
        }
    };

Log in to reply
 

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