forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0208-implement-trie-prefix-tree.ts
61 lines (51 loc) · 1.24 KB
/
0208-implement-trie-prefix-tree.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
54
55
56
57
58
59
60
61
class TrieNode {
children: {};
endOfWord: boolean;
constructor() {
this.children = {};
this.endOfWord = false;
}
}
class Trie {
root: TrieNode;
constructor() {
this.root = new TrieNode();
}
insert(word: string): void {
let cur = this.root;
for (const c of word) {
if (!(c in cur.children)) {
cur.children[c] = new TrieNode();
}
cur = cur.children[c];
}
cur.endOfWord = true;
}
search(word: string): boolean {
let cur = this.root;
for (const c of word) {
if (!(c in cur.children)) {
return false;
}
cur = cur.children[c];
}
return cur.endOfWord;
}
startsWith(prefix: string): boolean {
let cur = this.root;
for (const c of prefix) {
if (!(c in cur.children)) {
return false;
}
cur = cur.children[c];
}
return true;
}
}
const trie = new Trie();
trie.insert('apple');
trie.search('apple'); // return True
trie.search('app'); // return False
trie.startsWith('app'); // return True
trie.insert('app');
trie.search('app'); // return True