Skip to content

Commit 0eaa04d

Browse files
committed
Add solution #127
1 parent fa86686 commit 0eaa04d

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@
131131
123|[Best Time to Buy and Sell Stock III](./0123-best-time-to-buy-and-sell-stock-iii.js)|Hard|
132132
124|[Binary Tree Maximum Path Sum](./0124-binary-tree-maximum-path-sum.js)|Hard|
133133
125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy|
134+
127|[Word Ladder](./0127-word-ladder.js)|Hard|
134135
128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium|
135136
131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium|
136137
133|[Clone Graph](./0133-clone-graph.js)|Medium|

solutions/0127-word-ladder.js

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 127. Word Ladder
3+
* https://leetcode.com/problems/word-ladder/
4+
* Difficulty: Hard
5+
*
6+
* A transformation sequence from word beginWord to word endWord using a dictionary
7+
* wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
8+
* - Every adjacent pair of words differs by a single letter.
9+
* - Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to
10+
* be in wordList.
11+
* - sk == endWord
12+
* Given two words, beginWord and endWord, and a dictionary wordList, return the
13+
* number of words in the shortest transformation sequence from beginWord to
14+
* endWord, or 0 if no such sequence exists.
15+
*/
16+
17+
/**
18+
* @param {string} beginWord
19+
* @param {string} endWord
20+
* @param {string[]} wordList
21+
* @return {number}
22+
*/
23+
var ladderLength = function(beginWord, endWord, wordList) {
24+
const set = new Set(wordList);
25+
let queue = [beginWord];
26+
let count = 1;
27+
28+
while (queue.length) {
29+
const group = [];
30+
31+
for (const word of queue) {
32+
if (word === endWord) {
33+
return count;
34+
}
35+
36+
for (let i = 0; i < word.length; i++) {
37+
for (let j = 0; j < 26; j++) {
38+
const str = word.slice(0, i) + String.fromCharCode(j + 97) + word.slice(i + 1);
39+
if (set.has(str)) {
40+
group.push(str);
41+
set.delete(str);
42+
}
43+
}
44+
}
45+
}
46+
47+
queue = group;
48+
count++;
49+
}
50+
51+
return 0;
52+
};

0 commit comments

Comments
 (0)