Simple C solution


  • 0
    T
    	int j;
    	for (j = i + 1; j < len; j++, i++) {
    		s[i] = s[j];
    	}
    
    	if (add_null) {
    		s[len - 1] = '\0';
    	}
    }
    
    
    void trimAll(char *s) {
      int i = 0;
      int len = strlen(s);
      int start = 1;
      int adjust = 0;
      while (i < len || s[i] != '\0') {
    	 if (start && s[i] == 32) {
    		collapse(s, i, len, 1);
    		continue;
    	 } 
    	 start = 0;
    	 if (s[i] == 32 && s[i+1] == 32) {
    		 collapse(s, i+1, len, 1); 
    		 continue;
    	 }
    	
    	 if (s[i] == 32 && s[i+1] == '\0') {
    	    s[i] = '\0';
    	    break;
    	 }
    
    	 i++;
      }
    
    }
    
    void reverseString(char *s, int start, int end) {
        if (s == NULL) {
            return;
        }
        int len = end - start + 1;
        while (start < end) {
            char tmp = s[start];
            s[start] = s[end];
            s[end] = tmp;
            start++;
            end--;
        }
    }
    
    void reverseWords(char *s) {
        if (s == NULL) {
            return;
        }
    
    	int len = strlen(s);    
            reverseString(s, 0, len - 1);
    	int i;
    	int start = 0, end = 0;
    	for (i = 0; i <= len; i++) {
    		if (s[i] == ' ' || s[i] == '\0') {
    			reverseString(s, start, end - 1);
    			start = i + 1;
    		}
    	
    		end++;		
        }
    
        trimAll(s);
    
    }
    

Log in to reply
 

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