【leetcode hot 100 208】实现Trie(前缀树)

解法一:字典树

Trie,又称前缀树或字典树,是一棵有根树,其每个节点包含以下字段:

  • 指向子节点的指针数组 children。对于本题而言,数组长度为 26,即小写英文字母的数量。此时 children0 对应小写字母 a,children1 对应小写字母 b,...,children25 对应小写字母 z。
  • 布尔字段 isEnd,表示该节点是否为字符串的结尾。
java 复制代码
class Trie {

    private Trie[] children;
    private boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
    
    public void insert(String word) {
        Trie node = this;  //Trie node = this 而不是new
        for(int i=0; i<word.length(); i++){
            char ch = word.charAt(i);
            int num = ch - 'a'; 
            // 注意这里要判断node.children[num] == null)
            if(node.children[num] == null){
                node.children[num] = new Trie();
            }
            node = node.children[num];
        }
        node.isEnd = true;
    }
    
    public boolean search(String word) {
        Trie node = searchprefix(word);
        return node!=null && node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        return searchprefix(prefix)!=null;
    }

    public Trie searchprefix(String prefix){
        Trie node = this;
        for(int i=0; i<prefix.length(); i++){
            char ch = prefix.charAt(i);
            int num = ch - 'a';
            if(node.children[num]==null){
                return null;
            }
            node = node.children[num];
        }
        return node;
    }
}

注意:

  • 在插入算法中,当node.children[num] == null时(node.children[num] != null说明有相同前缀),才新建nodenode.children[num] = new Trie()
  • 要Trie node = this,而不是Trie node = new Trie()
相关推荐
cjz389911 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
橘子1314 小时前
【高级数据库】关系代数基本概念
算法
电科_银尘1 天前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David1 天前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
LK_071 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi1 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK1 天前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
zdr尽职尽责1 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
文丑颜不良啊1 天前
LeetCode3341~3360题目解析
java·leetcode