leetcode 127题 word ladder 疑问

leetcode题目 https://leetcode.com/problems...
自己在本地跑ok,提交总是失败,对失败的case,在本地测试也是ok的,求助帮忙看看是什么问题?
另外,在页面上只看到有提交按钮,没有测试跑本地case的按钮了,这个是咋回事?
我的代码如下:

class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
        if (beginWord == endWord) { return 0; }
        if (beginWord.length() == 0) { return 0; }
        wordList.erase(beginWord);
        deque<string> q;
        int step = 1;
        q.push_back(beginWord);
        q.push_back("");
        while (!q.empty()) {
            string s = q.front();
            q.pop_front();
            if (s == "") {
                if (q.empty()) { return 0; }
                q.push_back("");
                step++;
                continue;
            }
            //cout << "s=" << s << endl; 
            for (int w_i = 0; w_i < s.length(); w_i++) {
                char ch = s[w_i];
                for (char ch_i = 'a'; ch_i <= 'z'; ch_i++) {
                    if (ch_i == ch) { continue; }
                    s[w_i] = ch_i;
                    if (s == endWord) {
                        //cout << "find s=" << s << endl;
                        return step; 
                    }
                    if (wordList.find(s) != wordList.end()) {
                        q.push_back(s);
                        wordList.erase(s);
                        //cout << "new s=" << s << endl;
                    }
                    s[w_i] = ch;
                }
            }
        }
        return 0;
    }
};
阅读 2.8k
1 个回答

已经找到原因。judge的答案自身对链长计算是多算了一次的。比如
"hot", "dog", ["hot","dog","dot"]
这个case的路径是 hot->dot->dog, 这里是变化了两次,但是链长是三。judge要求的答案是三,而不是二。
将上面的代码,初始值step赋值为2,既可以ac了。对标准judge的不严谨真是无语了,还不提供反馈通道。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进