[For discussion] 2 ms, C implementation


  • 0
    K
    char temp; /*for character swapping*/
    
    void reverseWords(char *s) {
        char* p1 = s;
        char* p2 = s;
        int count = 0;
        int shifted = 0;
        
        while(*p1 != 0){
            if(*p1 != ' '){
                p2 = p1+1;
                while(*p2 != ' ' && *p2 != 0){
                    p2++;
                }
                swap(p1,p2-1);
                shift(p1,p2-1,count);
    			shifted = 1;
    			p1 = p2-count;
    			count = -1;/*except for the first word, every word shift by (number_of_space - 1)*/
            }
            else{
                p1++;
                count++;
            }
        }
        if (shifted ==1){
            shift(p1,p1,count+1);
        }
        else{
            shift(p1,p1,count);
        }
        
        for(p1=s,p2=s;*p2!=0;p2++);
    	swap(p1,p2-1); /*every word is swapped twice*/
    }
    
    void swap(char*p1,char*p2){
        while (p1<p2){
            temp = *p1;
            *p1 = *p2;
            *p2 = temp;
            ++p1;
            --p2;
        }
    }
    
    void shift(char*p1,char*p2,int N){
        if (N==0)
            return;
        else {
            for(;p1<=p2;p1++){
                *(p1-N) = *p1;
                *p1 = ' ';
            }
        }
    }

Log in to reply
 

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