deno.land / x / masx200_leetcode_test@10.6.5 / concatenated-words / 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
import { PrefixTreeInsert,} from "../design-add-and-search-words-data-structure/PrefixTreeInsert.ts";import { PrefixTree } from "../implement-trie-prefix-tree/PrefixTree.ts";
export default function findAllConcatenatedWordsInADict( words: string[],): string[] { const root = PrefixTree(); const ans: string[] = new Array(0); words.sort((a, b) => (a.length - b.length)); for (const word of words) { if (word.length == 0) { continue; } if (dfs(root, word, new Set())) { ans.push(word); } else { PrefixTreeInsert(root, word); } } return ans;}
function dfs(root: PrefixTree, word: string, visited: Set<string>): boolean { if (word.length == 0) { return true; } if (visited.has(word)) { return false; } visited.add(word);
let node: PrefixTree | undefined = root; for (let i = 0; i < word.length; i++) { const ch = word.charAt(i);
node = node.children.get(ch); if (!node) { return false; } if (node.isEnd) { if (dfs(root, word.slice(i + 1), visited)) { return true; } } } return false;}
masx200_leetcode_test

Version Info

Tagged at
a year ago