Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
var Trie = function() {
this.nodes = {};
};
Trie.prototype.insert = function(word) {
let node = this.nodes, cur;
for (let i = 0; i < word.length; i++) {
cur = word[i];
if (!node[cur]) {
node[cur] = {};
}
node = node[cur];
}
node.isWord = true;
};
Trie.prototype.search = function(word) {
let node = this.nodes, cur;
for (let i = 0; i < word.length; i++) {
cur = word[i];
if (!node[cur]) {
return false;
}
node = node[cur];
}
return node.isWord == true;
};
Trie.prototype.startsWith = function(prefix) {
let node = this.nodes, cur;
for (let i = 0; i < prefix.length; i++) {
cur = prefix[i];
if (!node[cur]) {
return false;
}
node = node[cur];
}
return true;
};