代码如下
思路:
- insert 将字符串解析为对象嵌套,例如
"abc"解析为this.obj={a:{b:{c:{isEnd:true}}}} - 再次插入
"abcd时",进一步解析为this.obj = {a:{b:{c:{isEnd:true,d:{isEnd:true}}}}}
var Trie = function () {
this.obj = {};
};
Trie.prototype.insert = function (word) {
var node = this.obj;
for (var s of word) {
if (!node[s]) {
node[s] = {};
}
node = node[s];
}
node.isEnd = true;
};
Trie.prototype.searchPrefix = function (prefix) {
var node = this.obj;
for (var s of prefix) {
if (!node[s]) {
return false;
}
node = node[s];
}
return node;
}
Trie.prototype.search = function (word) {
var node = this.searchPrefix(word);
return node && node.isEnd !== undefined;
};
Trie.prototype.startsWith = function (prefix) {
return this.searchPrefix(prefix);
};
var trie = new Trie()
trie.insert("abc")
trie.insert("abcd")
console.log(trie.search("abcd"));