deno.land / x / masx200_leetcode_test@10.6.5 / word-ladder / index.ts

نووسراو ببینە
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
export default 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;}
masx200_leetcode_test

Version Info

Tagged at
a year ago