【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()
相关推荐
2501_945424803 分钟前
高性能计算资源调度
开发语言·c++·算法
Tisfy11 分钟前
LeetCode 1594.矩阵的最大非负积:动态规划O(mn)
leetcode·矩阵·动态规划·dp
2301_7765087211 分钟前
C++中的组合模式变体
开发语言·c++·算法
Frostnova丶14 分钟前
LeetCode 1594.矩阵中最大的非负乘积
算法·leetcode·矩阵
We་ct15 分钟前
LeetCode 162. 寻找峰值:二分高效求解
前端·算法·leetcode·typescript·二分·暴力
丶小鱼丶15 分钟前
数据结构和算法之【二叉树】
java·数据结构·算法
星河Cynthia15 分钟前
WPF基于resx资源文件的多语言实现
c#·wpf
hanlin0315 分钟前
刷题笔记:力扣第38题-外观数列
算法·leetcode
2301_7938046918 分钟前
模板代码安全性增强
开发语言·c++·算法
测试_AI_一辰19 分钟前
Agent & RAG 测试工程笔记 13:RAG检索层原理拆解:从“看不懂”到手算召回过程
人工智能·笔记·功能测试·算法·ai·ai编程