3 ms C solution using own version of reverseString & trim - time O(n) , space O(1)


  • 1
    A
    void reverseString(char * start, char * end){
        
        while(start < end){
            char swap = *end;
            *end = *start;
            *start = swap;
            start++;
            end--;
        }
    }
    
    void removeLeadingTrailingRepeatSpaces(char * s){
    
        char * src= s;
        char * dst = s;
        bool isSentenceBoundary = true;
        while(*src != '\0'){
            
            if(*src == ' ' && isSentenceBoundary){
                src++;
                continue;
            }else{
                isSentenceBoundary = false ; 
            }
            
            if( *src == ' ' && ( *src == *(src+1)  || *(src+1) == '\0' )  ){
                src++;
                continue;
            }
            
            *dst = *src;
            dst++;
            src++;
        }
        *dst = *src;    
    }
    void reverseWords(char *s) {
        
        
        char * wordStart = s ; 
        char * wordEnd   = s ;
        char * p = s; 
        
        while(*p != '\0'){
            p++;
        }
        wordEnd = p - 1 ;
        
        reverseString(wordStart, wordEnd); //reverse whole string in place
        
        p = s; 
        bool withinWordBoundary = false;
        while(*p != '\0'){
            
            if(*p == ' ' && withinWordBoundary == true){
    
                withinWordBoundary = false;
                wordEnd = p - 1; 
                reverseString(wordStart,wordEnd);
                
            }else if(*p == ' ' && withinWordBoundary == false) {
                
            }else if(*p != ' ' && withinWordBoundary == true) {
                
            }else if(*p != ' ' && withinWordBoundary == false) {
                wordStart = p ;
                withinWordBoundary = true;
            }
            
            p++;
        }
        
        if(withinWordBoundary == true){
            wordEnd = p - 1;
            reverseString(wordStart,wordEnd);
        }
        
        removeLeadingTrailingRepeatSpaces(s);
    }

  • 0
    X
    This post is deleted!

Log in to reply
 

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