[Help] In what case I may get a Output Limit Exceeded


  • 0
    T
    void reverseWords(string &s) {
        string res = "";
        int lastPos = s.size();//last space position
        for(int i = s.size() - 1; i >= 0; --i)
        {
            if(s[i] == ' ')
                lastPos = i;
            else if(i==0||s[i-1] != ' ')//now this i is the first letter of a word
            {
                if(!res.empty())
                    res.append(" ");
                res.append(s.substr(i, lastPos - i));
            }
        }
        s = res;
    }
    

    I don't see any bugs in my code. Anyone could help me?


  • 0
    S

    According to the comment in code,

    else if(i==0||s[i-1] != ' ')//now this i is the first letter of a word
    

    should be

    else if(i==0||s[i-1] == ' ')//now this i is the first letter of a word
    

  • 0
    A

    I have very similar code and am getting the same result, "Output Limit Exceeded". My code doesn't have the bug mentioned in Shangrila's solution. What gives?


  • 0
    A

    Ahh, figured it out. In my use of substr, I wasn't passing the length as the second argument, I was passing the index after the end of the substring I wanted, much like copy. My bad.


Log in to reply
 

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