C - reverse words


  • 0
    S
    #define and &&
    
    void reverse_helper(char* s, int start, int end)
    {
        char c;
        while(start < end)
        {
            c = s[start];
            s[start] = s[end];
            s[end] = c;
            ++start, --end;
        }
    }
    void reverseWords(char *s) {
        
        int start = 0, end = 0, len = strlen(s);
        
        /*
         * reverse the entire string
         */
        reverse_helper(s, 0, len-1);
    
        while(end < len)
        {
            while(start < len and s[start] == ' ') ++start;
            
            end = start;
            while(end < len and s[end] != ' ') ++end;
            
            /*
             * reverse each word
             */
            reverse_helper(s, start, end-1);
            start = end;
        }
        
    }
    

Log in to reply
 

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