Runtime Error on " "


  • 0
    J

    I got Runtime Error on " ". But I don't understand why. I have end>=0 check in each of the 3 while loops, so the string []operator should be valid. Please help me to figure out the error. Thanks,

    class Solution {
    public:
        void reverseWords(string &s) {
            if (s.empty()) return;
            string outputall;
            size_t end = s.size()-1;
            while (end>=0) {
                //remove tailing spaces
                while (end>=0&&s[end] == ' ') end--;
                if(end<0) break;
                //add a space between word
                if(!outputall.empty()) outputall += ' ';
                //append a word
                while(end>=0&&s[end] != ' ') {
                    outputall += s[end];
                    end--;
                }
            }
            //assign output back to s
            if(outputall.empty()) {
                s = " ";
            } else {
                s = outputall;
            }
        }
    };

  • 1
    M

    You have a couple issues with your algorithm, but the one blocking you right now is that size_t is an unsigned int. It will never be less than 0, so when you have a length zero and decrement it, you get MAX_INT instead, taking you into memory you don't have permission to access. Switch size_t to int and you should be able to advance.


  • 0
    J

    Thanks a lot. Could you please point out other issues? Thanks.


  • 0
    M

    s = " " should be the empty string, "". There's a test case about that.

    You're also reversing the words themselves inside:
    while(end>=0&&s[end] != ' ') {
    outputall += s[end];
    end--;
    }

    To easily undo that, at the very end, reverse the string.


Log in to reply
 

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