【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()
相关推荐
你怎么知道我是队长13 小时前
C语言---循环结构
c语言·开发语言·算法
艾醒13 小时前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
纪元A梦15 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_15 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
mark-puls16 小时前
C语言打印爱心
c语言·开发语言·算法
Python技术极客16 小时前
将 Python 应用打包成 exe 软件,仅需一行代码搞定!
算法
吃着火锅x唱着歌16 小时前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun16 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌16 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
mudtools16 小时前
.NET驾驭Word之力:COM组件二次开发全攻略之连接Word与创建你的第一个自动化文档
后端·c#