C++ solution,in place with explaination


  • 0
    H

    This is my solution depend on other in place solutions

    class Solution {
    public:
       	void reverseWords(string &s) {
    
    		int length = s.length();
    		reverse(s.begin(),s.end());
    
    		int read = 0;
    		int write = 0;
    		while(read < length)
    		{
    		    //skip leading white space and more than one white spaces between words
    			if(s[read] == ' ')
    				++read;
    			else
    			{
    			    //record the start of a word
    				int wordStart = read;
    				//count the length of a word
    				while(read < length && s[read] != ' ')
    					++read;
    				//reverse  current word	
    				reverse(s.begin() + wordStart,s.begin() + read);
    				//copy current word to the appropriate position
    				copy(s.begin() + wordStart,s.begin() + read,s.begin() + write);
    				//move write to the end of current word
    				write += read - wordStart;
    				//add white space between words
    				if(write < length)
    					s[write] = ' ';
    				//move write one step forward	
    				++write;
    			}
    		}
    		//s is not a empty string or string of white spaces
           if (write)
    		{
    			s = s.substr(0,write-1);
    		}
    		else
    			s = "";
    		
    
    
    	}
    };
    

Log in to reply
 

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