mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #1809 from wang2jun/master
添加 127单词接龙 TypeScript 版本代码
This commit is contained in:
@ -247,6 +247,55 @@ var ladderLength = function(beginWord, endWord, wordList) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## TypeScript
|
||||||
|
```typescript
|
||||||
|
function ladderLength(
|
||||||
|
beginWord: string,
|
||||||
|
endWord: string,
|
||||||
|
wordList: string[]
|
||||||
|
): number {
|
||||||
|
const words = new Set(wordList);
|
||||||
|
if (!words.has(endWord)) return 0;
|
||||||
|
if (beginWord.length === 1) return 2;
|
||||||
|
let current = new Set([beginWord]);
|
||||||
|
let rightcurrent = new Set([endWord]);
|
||||||
|
words.delete(endWord);
|
||||||
|
let step = 1;
|
||||||
|
while (current.size) {
|
||||||
|
if (current.size > rightcurrent.size) {
|
||||||
|
[current, rightcurrent] = [rightcurrent, current];
|
||||||
|
}
|
||||||
|
const temp: Set<string> = new Set();
|
||||||
|
for (const word of current) {
|
||||||
|
for (const right of rightcurrent) {
|
||||||
|
if (diffonechar(word, right)) {
|
||||||
|
return step + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const other of words) {
|
||||||
|
if (diffonechar(other, word)) {
|
||||||
|
temp.add(other);
|
||||||
|
|
||||||
|
words.delete(other);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (temp.size === 0) return 0;
|
||||||
|
current = temp;
|
||||||
|
step = step + 1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function diffonechar(word1: string, word2: string): boolean {
|
||||||
|
let changes = 0;
|
||||||
|
for (let i = 0; i < word1.length; i++) {
|
||||||
|
if (word1[i] != word2[i]) changes += 1;
|
||||||
|
}
|
||||||
|
return changes === 1;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
|
Reference in New Issue
Block a user