Getting runtime error but run successfully on my laptop. Can someone explain this?


  • 0
    Z

    I can run the code in my machine but I keep getting runtime error for the test:

    "hit"
    "cog"
    ["hot","cog","dot","dog","hit","lot","log"]
    

    Can someone explain the bug in the code below? Thank you!

    class Solution {
    public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
        if (beginWord == endWord) {
            return 1;
        }
        if (updateOnce(beginWord, endWord)) {
            return 2;
        }
        if (wordList.count(beginWord)) {
            wordList.erase(beginWord);
        }
        queue<string> Q;
        int num = 1;
        string start = beginWord;
        Q.push(beginWord);
        while (!Q.empty()) {
            string word = Q.front();
            Q.pop();
            if (word == start) {
                num++;
                start = "";
            }
            for (unordered_set<string>::iterator it = wordList.begin(); it != wordList.end(); it++) {
                if (updateOnce(*it, word)) {
                    if (updateOnce(*it, endWord)) {
                        num++;
                        return num;
                    }
                    Q.push(*it);
                    wordList.erase(*it);
                    if (start == "") {
                        start = *it;
                    }
                }
            }
        }
        return 0;
    }
    private:
    bool updateOnce(string str1, string str2) {
        int update = 0;
        for (int i = 0; i < str1.size(); i++) {
            if (str1[i] != str2[i]) {
                update++;
                if (update > 1) {
                    return false;
                }
            }
        }
        return update == 1;
    }
    };

  • 1
    A
    for (unordered_set<string>::iterator it = wordList.begin(); it != wordList.end(); it++) {
            ...
            wordList.erase(*it);
    

    it's unsafe to erase *it during the for run


Log in to reply
 

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