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

解法一:字典树

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

  • 指向子节点的指针数组 children。对于本题而言,数组长度为 26,即小写英文字母的数量。此时 children[0] 对应小写字母 a,children[1] 对应小写字母 b,...,children[25] 对应小写字母 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()
相关推荐
Khsc434ka几秒前
.NET 10 与智能体时代的架构演进:以 File-Based Apps 为核心的 C# 生态重塑
架构·c#·.net
生信研究猿5 分钟前
94. 二叉树的中序遍历 (二叉树遍历整理)
数据结构·算法
挂科边缘6 分钟前
image-restoration-sde复现,图像修复,使用均值回复随机微分方程进行图像修复,ICML 2023
算法·均值算法·ir-sde·扩散模块图像修复
2301_822703206 分钟前
开源鸿蒙跨平台Flutter开发:血氧饱和度数据降噪:基于滑动窗口的滤波算法优化-利用动态列队 (Queue) 与时间窗口平滑光电容积脉搏波 (PPG)
算法·flutter·华为·开源·harmonyos
Vin0sen7 分钟前
算法-线段树与树状数组
算法
sycmancia12 分钟前
QT——计算器核心算法
开发语言·qt·算法
倦王13 分钟前
力扣日刷45
算法·leetcode·职场和发展
jackylzh16 分钟前
C# 中 LINQ 和 Lambda 表达式的 基本用法
c#
炽烈小老头16 分钟前
【 每天学习一点算法 2026/04/06】常数时间插入、删除和获取随机元素
学习·算法
阿Y加油吧19 分钟前
回溯算法双杀:子集 + 电话号码的字母组合 | 经典模板题解析
算法·leetcode