-
Notifications
You must be signed in to change notification settings - Fork 0
/
127.js
32 lines (28 loc) · 1009 Bytes
/
127.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
var ladderLength = function (beginWord, endWord, wordList) {
const set = new Set(wordList)
let queue = [beginWord];
let steps = 1;
while (queue.length) {
const next = [];
console.log(queue);
// loop over each word in the queue
for (let word of queue) {
if (word === endWord) return steps;
// loop over each char of the word
for (let i = 0; i < word.length; i++) {
// and replace the char with letters from [a - z]
for (let j = 0; j < 26; j++) {
const newWord = word.slice(0, i) + String.fromCharCode(j + 97) + word.slice(i + 1);
// if the new word exist in the word list add it to the queue
if (set.has(newWord)) {
next.push(newWord);
set.delete(newWord);
}
}
}
}
queue = next
steps++;
}
return 0;
};