-
-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathtrie.js
56 lines (51 loc) · 1.18 KB
/
trie.js
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
class Node {
constructor() {
this.children = {};
this.isEnd = false;
}
}
class Trie {
constructor() {
this.root = new Node();
}
//TC: O(n) SC: O(n)
insert(word) {
let curr = this.root;
for(let ch of word) {
if(!(ch in curr.children)) {
curr.children[ch] = new Node();
}
curr = curr.children[ch];
}
curr.isEnd = true;
}
//TC: O(n) SC: O(1)
search(word) {
let curr = this.root;
for(let ch of word) {
if(!(ch in curr.children)) {
return false;
}
curr = curr.children[ch];
}
return curr.isEnd;
}
//TC: O(n) SC: O(1)
startsWith(prefix) {
let curr = this.root;
for(let ch of prefix) {
if(!(ch in curr.children)) {
return false;
}
curr = curr.children[ch];
}
return true;
}
}
let trie = new Trie();
trie.insert("apple");
console.log(trie.search("apple"));
console.log(trie.search("app"));
console.log(trie.startsWith("app"));
trie.insert("app");
console.log(trie.search("app"));