一、题目描述
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/853ac2c91f7c4ecf227eb48d34ac5fc8.png)
二、示例
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3e4e3f3af5d6b1352f53992c15d41160.png)
三、解题思路
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7685b84a9f18208a81d292259a307c9e.png)
如图所示,比较前缀树比较类似于二叉树,主要的区别是在于前缀树每一个可以产生存在26个节点,而二叉树则
产生2个节点一个是左节点,另一个是右节点。
插入单词的思路:遍历单词的每一个字符,不断地进行迭代(在图中是自上而下的过程)。在每一个节点需要保
存一个isEnd来确保是否是单词结束的位置,如果单词在该节点结束,则isEnd设置为true.
查询单词的思路:遍历单词中的每一个字符,不断的进行迭代(在图中为自上而下的过程)。在过程中如果不存在该字符所对应的节点,则直接返回false,如果存在并且到达单词的最后,判断isEnd是否为true。
判断是否存在以某一个单词片段开头:遍历每一个单词,不断地进行迭代(在图中为自上而下的过程)。在过程中如果不存在该字符所对应的节点,则直接返回false。
四、代码展示
var Trie = function() {
this.root = {}
};
Trie.prototype.insert = function(word) {
let node = this.root
for(let i of word) {
if(!node[i]) {
node[i] = {}
}
node = node[i]
}
node.isEnd = true
};
Trie.prototype.search = function(word) {
let node = this.root
for(let i of word) {
if(!node[i]) {
return false
}
node = node[i]
}
return node.isEnd ? true : false
};
Trie.prototype.startsWith = function(prefix) {
let node = this.root
for(let i of prefix) {
if(!node[i]) {
return false
}
node = node[i]
}
return true
};