「前端刷题」208.实现 Trie (前缀树)(MEDIUM)

1,489 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第7天,点击查看活动详情

题目(Implement Trie (Prefix Tree))

链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree
解决数:1390
通过率:72%
标签:设计 字典树 哈希表 字符串 
相关公司:amazon google microsoft 

Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

请你实现 Trie 类:

  • Trie() 初始化前缀树对象。
  • void insert(String word) 向前缀树中插入字符串 word 。
  • boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
  • boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。

 

示例:

输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]

解释
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // 返回 True
trie.search("app");     // 返回 False
trie.startsWith("app"); // 返回 True
trie.insert("app");
trie.search("app");     // 返回 True

 

提示:

  • 1 <= word.length, prefix.length <= 2000
  • word 和 prefix 仅由小写英文字母组成
  • insertsearch 和 startsWith 调用次数 总计 不超过 3 * 104 次

思路

本题这字符集长度是26,即26个小写英文字母,isEnd表示该节点是否是字符串的结尾。

  1. 插入字符串:从字段树的根节点开始,如果子节点存在,继续处理下一个字符,如果子节点不存在,则创建一个子节点到children的相应位置,沿着指针继续向后移动,处理下一个字符,以插入‘cad’为例
  2. 查找前缀:从根节点开始,子节点存在,则沿着指针继续搜索下一个子节点,直到最后一个,如果搜索到了前缀所有字符,说明字典树包含该前缀。子节点不存在就说明字典树中不包含该前缀,返回false。
  3. 查找字符串:和查找前缀一样,只不过最后返回的节点的isEnd是true,也就是说字符串正好是字典树的一个分支
  • 复杂度分析:时间复杂度,初始化为 O(1),其余操作为 O(S),s为字符串的长度。空间复杂度为O(T),T为字符集的大小,本题是26

js:

var Trie = function() {
    this.children = {};
};

Trie.prototype.insert = function(word) {
    let nodes = this.children;
    for (const ch of word) {//循环word
        if (!nodes[ch]) {//当前字符不在子节点中 则创建一个子节点到children的响应位置
            nodes[ch] = {};
        }
        nodes = nodes[ch];//移动指针到下一个字符子节点
    }
    nodes.isEnd = true;//字符是否结束
};

Trie.prototype.searchPrefix = function(prefix) {
    let nodes = this.children;
    for (const ch of prefix) {//循环前缀
        if (!nodes[ch]) {//当前字符不在子节点中 直接返回false
            return false;
        }
        nodes = nodes[ch];//移动指针到下一个字符子节点
    }
    return nodes;//返回最后的节点
}

Trie.prototype.search = function(word) {
    const nodes = this.searchPrefix(word);
  	//判断searchPrefix返回的节点是不是字符串的结尾的字符
    return nodes !== undefined && nodes.isEnd !== undefined;
};

Trie.prototype.startsWith = function(prefix) {
    return this.searchPrefix(prefix);
};