Accepted in-place solution using C++


  • 0
    J
    class Solution {
    private:
    	void reverse(string &s, int i, int j){
    		char temp;
    		while (i < j)
    		{
    			temp = s[i];
    			s[i] = s[j];
    			s[j] = temp;
    			i++;
    			j--;
    		}
    	}
    public:
    	void reverseWords(string &s) {
    		if (s.length() == 0)
    		{
    			return;
    		}
    
    		int start = 0;
    		while (s[start] == ' ') start++;
    
    		int finalStart = start;
    		int end = start;
    
    		while (end < s.length())
    		{
    			//Find a word
    			while (s[end] != ' ' && end < s.length()) end++;
    
    			//Reverse the word
    			reverse(s, start, end - 1);
    
    			//Set new start and keep a blank
    			while (s[start] != ' ' && start < end) start++;
    			start++;
    
    			//End pass all following blanks
    			while (s[end] == ' ' && end < s.length()) end++;
    		}
    
    		--end;
    		while (s[end] == ' ') --end;
    
    		s = s.substr(finalStart, end - finalStart + 1);
    		reverse(s, 0, s.length() - 1);
    	}
    };

Log in to reply
 

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