C in place


  • 0
    L
    void reverse(char* begin, char* end){
    	while(begin<end){
    		*begin = *begin ^ *end;
    		*end = *begin ^ *end;
    		*begin = *begin ^ *end;
    		begin++;
    		end--;
    	}
    }
    
    void move(char* wordBegin, char* p, char* q){
    	while(p<=q){
    		*wordBegin++ = *p++;
    	}
    }
    
    void reverseWords(char *s) {
    	char* p = s;
    	char* wordBegin = s;
    	while(*p!='\0'){
    		while(*p==' '){
    	    	p++;
    	    }
    	    char* q = p;
    	    while(*q!=' ' && *q!='\0'){
    	    	q++;
    	    }
    	    q--;
    	    reverse(p, q);
    	    if(wordBegin<p){
    	    	move(wordBegin, p, q);
    	    }
    	    wordBegin += q - p + 1;
    	    p = q + 1;
    	    while(*p==' '){
    	    	p++;
    	    }
    	    if(*p=='\0'){
    	    	*wordBegin = '\0';
    	    }else{
    	    	*wordBegin++ = ' ';
    	    }
    	}
    	reverse(s, wordBegin-1);
    }
    

Log in to reply
 

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