4s in C++ by using pointer


  • 0
    S

    If this question is asked for using c++, the most efficient way is using pointer to scan the whole string.

    void reverse(char* begin, char* end){
    	while (begin <= end){
    		char tmp = *end;
    		*end = *begin;
    		*begin = tmp;
    		begin++;
    		end--;
    	}
    }
    void reverseWords(string &s) {
        char *begin = (char*)s.c_str();
    	char *tmp = begin+1;
    	while (*tmp != '\0'){
    		if (*tmp == ' ' && *(tmp - 1) != ' '){
    			reverse(begin, tmp - 1);
    			begin = NULL;
    		}
    		else if(begin == NULL && *tmp != ' '){
    			begin = tmp;
    		}
    		tmp++;
    	}
    
        if (begin){
    		reverse(begin, tmp - 1);
    	}
    	begin = (char *)s.c_str();
    	char *end = begin + s.length() - 1;
    	reverse(begin, end);
    }

Log in to reply
 

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