-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.js
More file actions
64 lines (55 loc) · 1.36 KB
/
Trie.js
File metadata and controls
64 lines (55 loc) · 1.36 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
class TrieNode {
constructor(prefix) {
this.links = {};
this.isWordEnd = false;
this.prefix = prefix != undefined ? prefix : "";
}
containsKey(char) {
return char in this.links;
}
get(char) {
return this.links[char];
}
put(char) {
this.links[char] = new TrieNode(this.prefix + char);
}
}
class Trie {
constructor(words) {
this.root = new TrieNode();
for (const word of words) {
this.insert(word);
}
}
insert(word) {
let node = this.root;
for (let i = 0; i < word.length; i++) {
const char = word[i];
if (!node.containsKey(char)) {
node.put(char);
}
node = node.get(char);
}
node.isWordEnd = true;
};
searchPrefix(word) {
let node = this.root;
for (let i = 0; i < word.length; i++) {
const char = word[i];
if (!node.containsKey(char)) {
return undefined;
}
node = node.get(char);
}
return node;
}
search(word) {
const node = this.searchPrefix(word);
return node != undefined && node.isEnd;
};
startsWith(prefix) {
return this.searchPrefix(prefix) != undefined;
};
}
exports.Trie = Trie;
exports.TrieNode = TrieNode;