力扣-208.实现Trie(前缀树)

题目链接

208.实现Trie(前缀树)

java 复制代码
class Trie {
    Trie[] children;
    boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }

    public void insert(String word) {
        Trie node = this;
        int len = word.length();
        for (int i = 0; i < len; i++) {
            int index = word.charAt(i) - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
            if (i == len - 1) {
                node.isEnd = true;
            }
        }
    }

    public boolean search(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            int index = word.charAt(i) - 'a';
            if (node.children[index] == null)
                return false;
            node = node.children[index];
        }
        return node.isEnd;
    }

    public boolean startsWith(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            int index = prefix.charAt(i) - 'a';
            if (node.children[index] == null)
                return false;
            node = node.children[index];
        }
        return true;
    }
}

小结:前缀树是一个类似26叉树,并有一个额外标记是否为字符串结尾,插入的时候用一个结点指针依次扫描字符串每一位,不存在则新建。

相关推荐
凤年徐5 分钟前
【数据结构与算法】刷题篇——环形链表的约瑟夫问题
c语言·数据结构·c++·算法·链表
张子夜 iiii18 分钟前
机器学习算法系列专栏:逻辑回归(初学者)
人工智能·算法·机器学习·逻辑回归
vivo互联网技术18 分钟前
慢SQL优化实战:从一例线上慢SQL探究执行引擎工作过程
数据库·mysql·算法
我想吃烤肉肉22 分钟前
leetcode-python-删除链表的倒数第 N 个结点
python·算法·leetcode·链表
flashlight_hi44 分钟前
LeetCode 分类刷题:16. 最接近的三数之和
javascript·数据结构·算法·leetcode
彭军辉1 小时前
什么是抽象主义人工智能?
人工智能·算法·语言模型·机器人
是店小二呀1 小时前
【动态规划 | 01背包】动态规划经典:01背包问题详解
算法·动态规划
黑色的山岗在沉睡1 小时前
P10480 可达性统计
数据结构·算法
魏嗣宗2 小时前
缓存系统扩展思考详解
前端·算法·架构
CoovallyAIHub2 小时前
无人机“飞得高”不等于“看得清”?无人机图像识别的算法真相来了!
深度学习·算法·计算机视觉