Help, I can't figure out what's wrong! It works well on my computer.


  • 0
    J
    void reverseWords(string &s) {
        int len = s.length();
        int i = len - 1, j = len;
        bool flag;
        //iterate from the end to the start
        while(i >= 0){
            //find the space reversely
            while(i >= 0 && s[i] != ' '){
                --i;
            }
            
            //between i and j is the non-space substring, cout
            flag = false;
            for(int k = i + 1; k < j; ++k){
                cout<<s[k];
                flag = true;
            }
            if(flag){
            	cout<<" ";
            }
            
            //change the j
            j = i;
            --i;
        }
    }

  • 0
    D

    You need to modify the string s in-place, not just print out the reversed content.


Log in to reply
 

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