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

相关推荐
信奥卷王1 分钟前
[GESP202503 六级] 树上漫步(含视频)
算法
Purple Coder22 分钟前
南京-我来啦
算法
w_zero_one27 分钟前
动态规划(三)
java·算法·动态规划
Logic10139 分钟前
C语言/数据结构贡献法题解:数组权值——所有连续子数组中不同数字个数之和(O(n)解法)
c语言·数据结构·算法·数组·时间复杂度·贡献法·哈希记录
DongQiShanRen40 分钟前
六根硬件映射(中):双站校验、生克闭环与驱动接口
数据库·人工智能·算法·rust·哈希算法·集成学习
mmmmath_31 小时前
LeetCode.637.二叉树的层平均值
算法·leetcode
青少儿编程课堂1 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会C/C++考级:并查集连通块与朋友圈问题解析
c++·python·算法·bfs·信息学竞赛
Tisfy1 小时前
LeetCode 2913.子数组不同元素数目的平方和 I:第一题先常数很大的O(n^2)
算法·leetcode·题解·模拟·暴力
罗湖老棍子1 小时前
[USACO05NOV] Asteroids G(洛谷-P7368)
算法·图论·二分图匹配·最大匹配·最小顶点覆盖
AI技术新视界1 小时前
Harness^2:递归自进化智能体Harnessing框架
人工智能·深度学习·算法·harness·rsi