How to modify my C++ solution to pass special test case "\space"


  • 0
    S
    class Solution {
    public:
        void reverseWords(string& s) {
            char *word_begin = NULL; //jump pointer
     
            char *cstr = new char[s.length() + 1];
            strcpy(cstr, s.c_str());
            char *temp = cstr;
            
            while(*temp){
                if((word_begin == NULL) && (*temp != ' '))
                {   //jump to real word begins
                    word_begin = temp;
                }
                if(word_begin && ((*(temp+1)) == ' ' ||(*(temp+1) == '\0')))
                {
                    reverse(word_begin, temp);
                    word_begin = NULL;
                }
                temp++;
            }
            reverse(cstr, temp-1);
        }
        
        void reverse(char* begin, char* end){
            char temp;
            while(begin<end){
                temp = *begin;
                *begin++ = *end;
                *end-- = temp;
            }
        }
    };

Log in to reply
 

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