C solution


  • 10
    L
    void reverse(int b, int e, char *s){
        while(b < e) {
            s[b] = s[b] ^ s[e];
            s[e] = s[b] ^ s[e];
            s[b] = s[b] ^ s[e];
            b++;
            e--;
        }
    }
    
    char* reverseWords(char* s) {
        int i, s_len = strlen(s), index = 0;
        
        for(i = 0; i <= s_len; i++) {
            if((s[i] == ' ') || (s[i] == '\0')){
                reverse(index, i - 1, s);
                index = i + 1;
            }
        }
        return s;
    }
    

  • 0
    B

    Code handles the situation about multiple writespaces.

    static void reverseOneWord(char *p1, char *p2) {
    	char c;
    	for (; p1 > p2; p1--, p2++) {
    		c = *p1;
    		*p1 = *p2;
    		*p2 = c;
    	}
    }
    
    char* reverseWords(char* s) {
    	char *p1, *p2;
    	for (p1 = s; *p1 && *p1 == ' '; p1++);
    	for (p2 = p1; *p1; p1++) {
    		if (*p1 != ' ')
    			continue; 
    		reverseOneWord(&p1[-1], p2);
    		for (; *p1 && *p1 == ' '; p1++);
    		if (!*p1)
    			break;
    		p2 = p1;
    	}
    	reverseOneWord(&p1[-1], p2);
    	return s;
    }
    

Log in to reply
 

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