11 ms, c++ solution


  • 0
    X
    class Solution {
    public:
        void reverseWords(string &s) {
            int len = s.length();
    		for(int i = 0; i < len/2; ++i)
    		{
    			char temp = s[i];
    			s[i] = s[len - 1 - i];
    			s[len - 1 - i] = temp;
    		}
    
    		int low = 0;
    		int high = 0;
    		while(high < len)
    		{
    			while(high < len && ' ' != s[high])
    				++high;
    			char temp;
    			for(int i = 0; i < (high - low)/2; ++i)
    			{
    				temp = s[low + i];
    				s[low + i] = s[high - 1 - i];
    				s[high - 1 - i] = temp;
    			}
    			low = ++high;
    		}
    
    		int i = 0;
    		while(' ' == s[i])
    			++i;
    		s = s.substr(i, string::npos);
    		i = s.length() - 1;
    		while(' ' == s[i])
    			--i;
    		s = s.substr(0, i + 1);
    		//cout << "s = " << s << endl;
    
    		bool space = false;
    		string res = "";
    		for(i = 0; i < s.length(); ++i)
    		{
    			if(' ' == s[i])
    			{
    				if(false == space)
    				{
    					space = true;
    					res.push_back(s[i]);
    				}
    			}
    			else
    			{
    				space = false;
    				res.push_back(s[i]);
    			}
    		}
    
    		s = res;
        }
    };

Log in to reply
 

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