-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path127 Word Ladder.js
More file actions
69 lines (60 loc) · 1.86 KB
/
Copy path127 Word Ladder.js
File metadata and controls
69 lines (60 loc) · 1.86 KB
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
66
67
68
69
// Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
// Only one letter can be changed at a time
// Each intermediate word must exist in the word list
// For example,
// Given:
// beginWord = "hit"
// endWord = "cog"
// wordList = ["hot","dot","dog","lot","log"]
// As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
// return its length 5.
// Note:
// Return 0 if there is no such transformation sequence.
// All words have the same length.
// All words contain only lowercase alphabetic characters.
// Amazon LinkedIn Snapchat Facebook Yelp
/**
* @param {string} beginWord
* @param {string} endWord
* @param {Set} wordList
* Note: wordList is a Set object, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
* @return {number}
*/
/**
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {number}
*/
// About 520ms faster than ~50% and 42.7MB less than ~70%
var ladderLength = function(beginWord, endWord, wordList) {
let result = 1;
const visited = new Set([beginWord]);
let queue = [];
const words = new Set(wordList);
queue.push(beginWord);
while (queue.length) {
const nextQueue = [];
for (let cur of queue) {
if (cur === endWord) {
return result;
}
const curArr = cur.split("");
for (let i = 0; i < curArr.length; i++) {
for (let j = 0; j < 26; j++) {
curArr[i] = String.fromCharCode(96 + j);
const newStr = curArr.join("");
if (!visited.has(newStr) && words.has(newStr)) {
nextQueue.push(newStr);
visited.add(newStr);
}
curArr[i] = cur[i];
}
}
}
queue = nextQueue;
result += 1;
}
return 0;
};