-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring-indexing.js
45 lines (40 loc) · 1.07 KB
/
string-indexing.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
/*
String indexing: Keep track of which web URLs have been visited.
Use the following methods:
insert: Inserts a word into the trie.
search: Returns if the word is in the trie and is a complete word.
startsWith: Returns if there is any word in the trie that starts with the given prefix.
*/
var Trie = function(char) {
this.root = {};
};
Trie.prototype.insert = function(word) {
let current = this.root;
for (let char of word) {
if (!current[char]) {
current[char] = {};
}
current = current[char];
}
current.isWord = true;
};
Trie.prototype.search = function(word) {
let current = this.root;
for (let char of word) {
if (!current.hasOwnProperty(char)) {
return false;
}
current = current[char];
}
return current.isWord === true;
};
Trie.prototype.startsWith = function(prefix) {
let current = this.root;
for (let char of prefix) {
if (!current.hasOwnProperty(char)) {
return false;
}
current = current[char];
}
return true;
};