Different result between OJ and my codeblocks


  • 0
    C

    To replace a letter in the word, you can

    string newword(word);
    newword[0] = 'a';
    

    or

    char *wordchar = new char[m + 1];
    copy(str.begin(), str.end(), wordchar);
    wordchar[0] = 'a';
    string newword(wordchar);
    

    Both methods run well in my local IDE

    • codeblocks 13.12
    • mingw32-g++.exe -std=c++11 -c word-ladder.cpp -o
    • word-ladder.o mingw32-g++.exe -o word-ladder.exe word-ladder.o

    However the latter method runs wrong answer in OJ with this case

    hot, dog, [hot, dog, dot]
    output: 0
    expect: 3
    

    What's wrong with it?

    BTW, I found 'count' is fast than 'find' in set, which seems interesting.

    The whole code

    class Solution {
    public:
        int ladderLength(string start, string end, unordered_set<string> &dict) {
            if (start == end) return 1;
            dict.insert(start);
            dict.insert(end);
    
            int i, j, n, m = start.size();
     //       char *wordchar = new char[m + 1];
            int ans = 1;
            unordered_set<string> vis;
            queue<string> que;
            que.push(start);
            while (!que.empty()){
                ans++;
                n = que.size();
                while (n--){
                    string str = que.front();
                    que.pop();
    //                copy(str.begin(), str.end(), wordchar);
                    for (i = 0; i < m; i++){
    //                    char org = wordchar[i];
                        for (char c = 'a'; c <= 'z'; c++){
    //                        wordchar[i] = c;
    //                        string ss(wordchar);
                            string ss(str);
                            ss[i] = c;
                            if (ss == end) return ans;
                            if (dict.count(ss) > 0 && vis.count(ss) == 0){
                                que.push(ss);
                                vis.insert(ss);
                            }
                        }
    //                    wordchar[i] = org;
                    }
                }
            }
            return 0;
        }
    };

Log in to reply
 

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