Skip to content

Commit 31192e9

Browse files
authored
Create 127-word-ladder.js
1 parent d1b7098 commit 31192e9

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

127-word-ladder.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {string} beginWord
3+
* @param {string} endWord
4+
* @param {string[]} wordList
5+
* @return {number}
6+
*/
7+
const ladderLength = function(beginWord, endWord, wordList) {
8+
const list = new Set(wordList)
9+
if (!list.has(endWord)) return 0
10+
let one = new Set([beginWord])
11+
let two = new Set([endWord])
12+
let step = 1
13+
while (one.size && two.size) {
14+
let temp = new Set()
15+
if (two.size < one.size) [one, two] = [two, one]
16+
for (const word of one) {
17+
for (let i = 0; i < word.length; i++) {
18+
for (let j = 0; j < 26; j++) {
19+
const candidate =
20+
word.slice(0, i) + String.fromCharCode(97 + j) + word.slice(i + 1)
21+
if (two.has(candidate)) return step + 1
22+
if (!list.has(candidate)) continue
23+
temp.add(candidate)
24+
list.delete(candidate)
25+
}
26+
}
27+
}
28+
;[one, temp] = [temp, one]
29+
step++
30+
}
31+
return 0
32+
}

0 commit comments

Comments
 (0)