Where is wrong? reverse words in a string

  • 0

    hello everyone, this is my solution, I have compiled it under unix g++ and it gives me a correct answer, however the leetcode told me this is wrong: Input: " " Output: " " Expected: "" I also tested my code using input string as " ", and the result is ""..that's wired..

    string reverseWords(string &s) {
            vector<string> vs;
            string s1="";
            for(int i = 0; i < s.length(); ++i){
                if(s.substr(i,1)!=" "){
                }else if(s1.length()>0){
            for(int i = 0; i < vs.size(); ++i){
                s1 += vs[vs.size() - i - 1];
                if(i<vs.size()-1)s1 += " ";
            return s1;

  • 2

    got it, string s is both input and output variable

  • 1

    I encountered the similar issue, I think it may because the string s is a reference, and it verifies s output.
    just assign s1 to s, you will get ACCEPTION

  • 0

    f**k, waste many time on it. How could I know that trick

Log in to reply

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