forked from akshitagit/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.js
More file actions
41 lines (37 loc) · 719 Bytes
/
Trie.js
File metadata and controls
41 lines (37 loc) · 719 Bytes
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
class Node {
constructor() {
this.children = {};
this.isWord = false;
}
}
class Trie {
constructor() {
this.root = new Node();
}
insert(word) {
let node = this.root;
for (let c of word) {
if (!node.children[c]) {
node.children[c] = new Node();
}
node = node.children[c];
}
node.isWord = true;
}
search(word) {
let node = this.root;
for (let c of word) {
if (!node.children[c]) return false;
node = node.children[c];
}
return node.isWord;
}
startsWith(prefix) {
let node = this.root;
for (let c of prefix) {
if (!node.children[c]) return [];
node = node.children[c];
}
return node;
}
}