【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()
相关推荐
wenhaoran114 分钟前
CF1800F Dasha and Nightmares
c++·算法·字符串·codeforces·位运算
We་ct7 分钟前
LeetCode 149. 直线上最多的点数:题解深度剖析
前端·javascript·算法·leetcode·typescript
sheeta19988 分钟前
LeetCode 每日一题笔记 日期:2026.04.13 题目:1848.到目标元素的最小距离
笔记·算法·leetcode
Anycall.Q12 分钟前
RULE (ICLR 2026)
算法
Tisfy14 分钟前
LeetCode 1848.到目标元素的最小距离:数组遍历(附python一行版)
python·leetcode·题解·遍历
断眉的派大星16 分钟前
数据结构——指针
数据结构·算法
Xpower 1718 分钟前
算法学习笔记 Day 1:迁移学习与域自适应(DANN/CORAL)
笔记·学习·算法
橘颂TA27 分钟前
【笔试】算法的暴力美学——牛客 NC242:单词搜索,思路:dfs 算法
算法·深度优先
南無忘码至尊42 分钟前
Unity学习90天-第3天-认识触屏输入(手游基础)并完成手机点击屏幕,物体向点击位置移动
学习·unity·c#·游戏引擎·游戏开发
沐苏瑶43 分钟前
Java据结构深度解析:AVL 树与红黑树
数据结构·算法