-
Notifications
You must be signed in to change notification settings - Fork 0
/
0127-WordLadder.js
65 lines (55 loc) · 1.77 KB
/
0127-WordLadder.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//-----------------------------------------------------------------------------
// Runtime: 120ms
// Memory Usage: 44.5 MB
// Link: https://leetcode.com/submissions/detail/385877147/
//-----------------------------------------------------------------------------
var solution = function() {
'use strict';
/**
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {number}
*/
var ladderLength = function(beginWord, endWord, wordList) {
const wordSet = new Set(wordList);
if (!wordSet.has(endWord)) {
return 0;
}
let steps = 1,
set1 = new Set([ beginWord ]),
set2 = new Set([ endWord ]);
while (set1.size > 0 && set2.size > 0) {
let next = [];
if (set1.size > set2.size) {
let temp = set1;
set1 = set2;
set2 = temp;
}
for (let word of set1) {
if (set2.has(word)) {
return steps;
}
for (let i = 0; i < word.length; i++) {
for (let j = 0; j < 26; j++) {
let cur = word.slice(0, i) + String.fromCharCode(j + 97) + word.slice(i + 1);
if (set2.has(cur)) {
return steps + 1;
}
if (wordSet.has(cur)) {
next.push(cur);
wordSet.delete(cur);
}
}
}
}
set1 = new Set(next);
steps++;
}
return 0;
};
return {
ladderLength: ladderLength
};
};
module.exports = solution();