【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()
相关推荐
一个不知名程序员www8 小时前
算法学习入门 --- 哈希表和unordered_map、unordered_set(C++)
c++·算法
Traced back8 小时前
# C# + SQL Server 实现自动清理功能的完整方案:按数量与按日期双模式
开发语言·c#
Sarvartha8 小时前
C++ STL 栈的便捷使用
c++·算法
yj爆裂鼓手9 小时前
c#万能变量
开发语言·c#
夏鹏今天学习了吗9 小时前
【LeetCode热题100(92/100)】多数元素
算法·leetcode·职场和发展
飞Link9 小时前
深度解析 MSER 最大稳定极值区域算法
人工智能·opencv·算法·计算机视觉
bubiyoushang88810 小时前
基于CLEAN算法的杂波抑制Matlab仿真实现
数据结构·算法·matlab
不绝19110 小时前
C#进阶:委托
开发语言·c#
喜欢喝果茶.10 小时前
跨.cs 文件传值(C#)
开发语言·c#
就是有点傻10 小时前
C#中如何和欧姆龙进行通信的
c#