My Solution to solve reversing words in String in O(1) space


  • 0
    T
    1. Trim whit-space
    2. Reverse the whole string
    3. Reverse every words

    {

    void trim(char* sb)  
    {  
    	char *pTmp = sb;  		
    	int headspace = sb[0] == ' ';
    
    	while (*sb != '\0')   
    	{  
    		if (*sb != ' ')
    		{  
    			if (*(sb-1) == ' ' && !headspace) 
    			{
    				*pTmp++ = ' ';
    			}
    			*pTmp++ = *sb;  
    			headspace = 0;
    		} 
    		++sb;		
    	}  
    	*pTmp = '\0';  
    }  
    
    void swapChar(char* s, int left, int right)
    {
    	while (left < right)
    	{
    		char ch = s[left];
    		s[left] = s[right];
    		s[right] = ch;
    		left++;
    		right--;
    	}
    }
    
    void reverseWords(char *s) 
    {
       	int end = 0;	
    	int start = 0;
    	int len;
    
    	trim(s);
    	len = strlen(s);
    	swapChar(s,0,len - 1);
    
    	for (;end < len; end++)
    	{
    		if (s[end] == ' ')
    		{			
    			swapChar(s,start,end-1);
    			start = end + 1;
    		}
    	}
    
    	swapChar(s,start,len-1); 
    }
    

    }


Log in to reply
 

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