-
Notifications
You must be signed in to change notification settings - Fork 0
/
word-ladder.js
50 lines (40 loc) · 966 Bytes
/
word-ladder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {number}
*/
var ladderLength = function(beginWord, endWord, wordList) {
var wordSet = new Set(wordList);
var queue = [];
var step = 0;
var word = '';
var len = 0;
var i = 0;
pushNextWord(beginWord, queue, wordSet);
step = 2;
while (len = queue.length) {
for (i = 0; i < len; i++) {
word = queue.shift();
if (word === endWord) return step;
pushNextWord(word, queue, wordSet);
}
step++;
}
return 0;
};
var pushNextWord = function (word, queue, wordSet) {
var start = 'a'.charCodeAt(0);
var len = word.length;
var str = '';
wordSet.delete(word);
for (var i = 0; i < len; i++) {
for (var j = 0; j < 26; j++) {
str = word.substr(0, i) + String.fromCharCode(j + start) + word.substr(i + 1);
if (wordSet.has(str)) {
queue.push(str);
wordSet.delete(str);
}
}
}
};