c in place ugly code O(1) space O(n) time


  • 0
    Y
    #include <stdio.h>
    #include <string.h>
    
    void swap(char *p1,char *p2){
        while(p1<p2){
            char c=*p2;*p2--=*p1;*p1++=c;
        }
    }
    
    void reverseWords(char *s) {
        char *p1=s,*p2=s-1,*head=s;
        int test=0;
        for(;*s!='\0';s++){
            if((*s)!=' '){ 
                test=1;
                *++p2=*s;
            }
            else if(test){ 
                test=0;
                swap(p1,p2);
                *++p2=*s;
                p1=p2+1;
            }
        }
        p2+=test+(p2<head);
        *p2='\0';
        swap(p1,p2-1);
        swap(head,p2-1);
    }
    

Log in to reply
 

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