【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()
相关推荐
叶子20242211 分钟前
守护进程实验——autoDL
人工智能·算法·机器学习
半桔39 分钟前
【算法深练】分组循环:“分”出条理,化繁为简
数据结构·c++·算法·leetcode·面试·职场和发展
天天爱吃肉821840 分钟前
【十年技术演进深度解构:车载充电机(OBC)将成为新能源汽车的“能源大脑”】
python·嵌入式硬件·算法·汽车·能源
KerwinChou_CN1 小时前
自由开发者计划 004:创建一个苹果手机长截屏小程序
图像处理·算法·智能手机·小程序
Kethy__1 小时前
算法分析与设计-动态规划、贪心算法
c++·学习·算法·贪心算法·动态规划
闪电麦坤952 小时前
数据结构:递归:泰勒展开式(Taylor Series Expansion)
数据结构·算法
Humbunklung8 小时前
Rust 控制流
开发语言·算法·rust
ghost1438 小时前
C#学习第27天:时间和日期的处理
开发语言·学习·c#
jason成都8 小时前
c#压缩与解压缩-SharpCompress
开发语言·c#
鑫鑫向栄9 小时前
[蓝桥杯]取球博弈
数据结构·c++·算法·职场和发展·蓝桥杯·动态规划