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

相关推荐
Jerry1 小时前
LeetCode 189. 轮转数组
算法
Jerry2 小时前
LeetCode 739. 每日温度
算法
2601_954526756 小时前
【工业传感与算法实战】温漂补偿与零点抗漂破局:基于二阶多项式拟合的 C/C++ 边缘校准算法,深度拆解“压力变送器什么牌子好”的技术硬指标
c语言·c++·算法
叩码以求索7 小时前
浅谈:算法萌新如何高效刷题应对面试(一)
算法·面试·职场和发展
c238569 小时前
把 C++ 内存分配拆透:new 与 malloc 的三层血缘
开发语言·c++·算法
aaaameliaaa10 小时前
指针之总结
c语言·笔记·算法
宵时待雨10 小时前
优选算法专题9:哈希表
数据结构·算法·散列表
txzrxz10 小时前
最短路问题——Dijkstra 算法
数据结构·c++·算法·最短路·优先队列
gwf21610 小时前
磨损均衡算法(Wear Leveling)——SSD如何让每块闪存“公平退休“?
运维·数据库·人工智能·python·嵌入式硬件·算法·智能硬件
noipp10 小时前
推荐题目:洛谷 P6231 [JSOI2013] 公交系统
c语言·数据结构·c++·算法·游戏·洛谷·luogu