【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()
相关推荐
zxbmmmmmmmmm13 分钟前
在 Avalonia 中编写高性能动画
c#·xaml·avalonia·compositon
MATLAB代码顾问14 分钟前
【智能优化】鹈鹕优化算法(POA)原理与Python实现
开发语言·python·算法
AI科技星30 分钟前
微积分:变化与累积的数学(分层大白话解释版)
人工智能·算法·数学建模·数据挖掘·机器人
sinat_2869451934 分钟前
llm wiki
人工智能·算法·chatgpt
博界IT精灵1 小时前
图的遍历(哈喜老师)
数据结构·考研·算法·深度优先
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2026.05.10 题目:2770. 达到末尾下标所需的最大跳跃次数
笔记·算法·leetcode
Halo_tjn1 小时前
基于异常处理机制 相关知识点
java·开发语言·算法
xingyuzhisuan1 小时前
适合微调Llama 3 70B模型的最低GPU配置推荐
运维·人工智能·算法·llama·gpu算力
IJCAST2 小时前
Exploring the Frontiers of Complexity: Latest Research from IJCAST
人工智能·深度学习·神经网络·算法
所以遗憾是什么呢?2 小时前
【题解】Codeforces Round 1097 (Div. 2, Based on Zhili Cup 2026) (致理杯) ABCDEF
数据结构·算法·acm·codeforces·icpc·ccpc·xcpc