forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoobing.ts
More file actions
53 lines (48 loc) · 1.13 KB
/
soobing.ts
File metadata and controls
53 lines (48 loc) · 1.13 KB
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
// 3rd tried
class TrieNode {
children: Map<string, TrieNode>;
isEnd: boolean;
constructor() {
this.children = new Map();
this.isEnd = false
}
}
class Trie {
root: TrieNode;
constructor() {
this.root = new TrieNode();
}
insert(word: string): void {
let node = this.root;
for(const ch of word) {
if(!node.children.has(ch)) {
node.children.set(ch, new TrieNode());
}
node = node.children.get(ch)!
}
node.isEnd = true;
}
search(word: string): boolean {
let node = this.root;
for(const ch of word) {
if(!node.children.has(ch)) return false;
node = node.children.get(ch)!;
}
return node.isEnd;
}
startsWith(prefix: string): boolean {
let node = this.root;
for(const ch of prefix) {
if(!node.children.has(ch)) return false;
node = node.children.get(ch)!;
}
return true;
}
}
/**
* Your Trie object will be instantiated and called as such:
* var obj = new Trie()
* obj.insert(word)
* var param_2 = obj.search(word)
* var param_3 = obj.startsWith(prefix)
*/