Why did my code get a wrong answer?


  • 0
    K

    I run my codes on chrome, the given inputs are as below:
    beginWord = 'hot';
    endWord = 'dog';
    wordDict = ['hot', 'dog', 'dot'];
    I got 3 as the correct result.
    But when I submit my code on leetcode, I got a wrong answer under the same inputs

    /**
     * @param {string} beginWord
     * @param {string} endWord
     * @param {set<string>} wordDict
     * @return {number}
    */
    var ladderLength = function(beginWord, endWord, wordDict) {
        var i, len = wordDict.length, lengthMap = {}, visited = [];
        if(beginWord === endWord) {
            return 1;
        }
        if(canTransform(beginWord, endWord)) {
            return 2;
        }
        lengthMap[beginWord] = 1;
        cur = beginWord;
        while(cur !== undefined) {
            for(i = 0; i < len; ++i) {
                curWord = wordDict[i];
                if(!lengthMap[curWord]) {
                    if(canTransform(cur, curWord)) {
                	visited.push(curWord);
                        lengthMap[curWord] = lengthMap[cur] + 1;
                        if(canTransform(curWord, endWord)) {
                            return lengthMap[curWord] + 1;
                        }
                    }
                }
            }
          cur = visited.shift();
        }
        return 0;
    };
    var canTransform = function(a, b) {
        var i, len = a.length;
        for(i = 0; i < len; ++i) {
            if(a[i] !== b[i]) {
                return a.substr(i + 1) === b.substr(i + 1);
            }
        }
    };

Log in to reply
 

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