【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()
相关推荐
学逆向的6 分钟前
汇编——位运算
开发语言·汇编·算法·网络安全
公子小六15 分钟前
基于.NET的Windows窗体编程之WinForms图像控件
windows·microsoft·c#·.net·winforms
可编程芯片开发20 分钟前
基于simulink的PEM燃料电池控制系统建模与仿真,对比PID,积分分离以及滑模控制器
算法
学究天人36 分钟前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷2)
算法·数学建模·动态规划·图论·抽象代数·拓扑学
吴可可1231 小时前
C# CAD自定义图元优化切割路径
c#
玛卡巴卡ldf1 小时前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
wanzehongsheng2 小时前
零碳产业园光伏园区光伏电站追踪对比固定:发电增益技术边界分析
算法·光伏发电·光伏·零碳园区·太阳能追光·低碳环保·追踪电站
KobeSacre2 小时前
CyclicBarrier 源码
java·jvm·算法
手写码匠2 小时前
注意力机制全家桶:从 Multi-Head 到 GQA 再到 Flash Attention 的手写实现
人工智能·深度学习·算法·aigc
大鱼>2 小时前
模型公平性与偏差检测:AI伦理实战指南
人工智能·深度学习·算法·机器学习