0ms C solution in place ,O(1) space O(n) time


  • 1
    H
    void reverse(char * s,int first, int last)
    {
        while(first < last)
        {
            char tmp = s[first];
            s[first++] = s[last];
            s[last--] = tmp;
        }
    }
    
    void reverseWords(char *s) {
        int last = 0, now = 0;
        while(s[now])
        {
            while(s[now] == ' ') now++;
            last = now;
            while( s[now] != ' ' && s[now]!= '\0') now++;
            reverse(s,last,now-1);
        }
       reverse(s,0,now-1);
       last = 0;/// delete duplicated blank
       for(int i = 0; i < now; i++)
           if(!isblank(s[i]) ||(last && s[last-1]!=s[i]) )
                s[last++] = s[i];
       s[last] = 0;
       if(last && s[last - 1] ==' ') 
           s[last-1] =0;
    }

Log in to reply
 

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