【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()
相关推荐
黄名富4 分钟前
深入探究 JVM 堆的垃圾回收机制(二)— 回收
java·jvm·算法·系统架构
炒鸡码力19 分钟前
一道原创OI题(普及-)——ZCS的随机游走
c++·算法·题解·模拟·题目
卧式纯绿39 分钟前
目标检测20年(二)
人工智能·深度学习·算法·yolo·目标检测·机器学习·目标跟踪
梭七y1 小时前
leetcode日记(105)买卖股票的最佳时机Ⅱ
算法·leetcode·职场和发展
MiyamiKK571 小时前
leetcode_双指针 11. 盛最多水的容器
python·算法·leetcode·职场和发展
不去幼儿园2 小时前
【强化学习】Reward Model(奖励模型)详细介绍
人工智能·算法·机器学习·自然语言处理·强化学习
Vacant Seat2 小时前
回溯-单词搜索
java·数据结构·算法·回溯
咩咩觉主2 小时前
Unity 使用Odin插件解决多层字典配置文件问题
unity·c#·游戏引擎
GeekPMAlex2 小时前
Python03 链表的用法
算法
IT从业者张某某2 小时前
机器学习-04-分类算法-02贝叶斯算法案例
算法·机器学习·分类