【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()
相关推荐
咕白m62519 小时前
使用 C# 设置 Word 段落对齐样式
后端·c#
ULTRA??19 小时前
STL deque 的详细特征
c++·算法
yongui4783419 小时前
MATLAB 二维方腔自然对流 SIMPLE 算法
人工智能·算法·matlab
武藤一雄19 小时前
[.NET] 中 System.Collections.Generic命名空间详解
windows·微软·c#·asp.net·.net·.netcore
kingwebo'sZone20 小时前
一次找不到“无法加载dll 对应的”,多媒体没有启用(需要安装mediaplayer)
c#
zxbmmmmmmmmm20 小时前
Avalonia源码解读:Grid(网格控件)
c#·xaml·avalonia
循着风20 小时前
环形子数组的最大和
数据结构·算法·leetcode
CoovallyAIHub20 小时前
如何让AI的数据标注“火眼金睛”?人机协同才是可靠途径
深度学习·算法·计算机视觉
wa的一声哭了20 小时前
拉格朗日插值
人工智能·线性代数·算法·机器学习·计算机视觉·自然语言处理·矩阵
gongfuyd20 小时前
傅里叶变换、拉普拉斯变换、Z 变换的定义及关系
算法·机器学习·概率论