-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.js
More file actions
77 lines (59 loc) · 1.45 KB
/
Copy pathtrie.js
File metadata and controls
77 lines (59 loc) · 1.45 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class TrieNode {
constructor() {
this.links = [];
this.end = false;
}
containsKey(char) {
return this.links[this.getCharCode(char)] !== undefined;
}
get(char) {
return this.links[this.getCharCode(char)];
}
put(char, node) {
this.links[this.getCharCode(char)] = node;
}
getCharCode(char) {
return char.charCodeAt(0) - 'a'.charCodeAt(0);
}
setEnd() {
this.end = true;
}
isEnd() {
return this.end;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
// Inserts word into trie
insert(word) {
let node = this.root;
for (let i = 0; i < word.length; i++) {
let currChar = word.charAt(i);
if (!node.containsKey(currChar)) node.put(currChar, new TrieNode());
node = node.get(currChar);
}
node.setEnd();
}
// Returns if the word is in the trie
search(word) {
const node = this.searchPrefix(word);
return node !== null && node.isEnd();
}
// Returns if there is any word in the trie that starts with the given prefix
startsWith(prefix) {
const node = this.searchPrefix(prefix);
return node !== null;
}
// Searches a prefix or whole key in trie and returns the node where search ends
searchPrefix(word) {
let node = this.root;
for (let i = 0; i < word.length; i++) {
let currChar = word.charAt(i);
if (node.containsKey(currChar)) node = node.get(currChar);
else return null;
}
return node;
}
}