力扣-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叉树,并有一个额外标记是否为字符串结尾,插入的时候用一个结点指针依次扫描字符串每一位,不存在则新建。

相关推荐
冯诺依曼的锦鲤几秒前
算法练习:差分
c++·学习·算法
有意义29 分钟前
栈数据结构全解析:从实现原理到 LeetCode 实战
javascript·算法·编程语言
鹿鹿鹿鹿isNotDefined34 分钟前
逐步手写,实现符合 Promise A+ 规范的 Promise
前端·javascript·算法
封奚泽优1 小时前
下降算法(Python实现)
开发语言·python·算法
im_AMBER1 小时前
算法笔记 16 二分搜索算法
c++·笔记·学习·算法
高洁011 小时前
【无标具身智能-多任务与元学习】
神经网络·算法·aigc·transformer·知识图谱
leoufung1 小时前
逆波兰表达式 LeetCode 题解及相关思路笔记
linux·笔记·leetcode
识醉沉香1 小时前
广度优先遍历
算法·宽度优先
中國龍在廣州1 小时前
现在人工智能的研究路径可能走反了
人工智能·算法·搜索引擎·chatgpt·机器人
快手技术2 小时前
NeurIPS 2025 | 可灵团队提出 Flow-GRPO, 首次将在线强化学习引入流匹配生成模型
算法