【leetcode hot 100 208】实现Trie(前缀树)

解法一:字典树

Trie,又称前缀树或字典树,是一棵有根树,其每个节点包含以下字段:

  • 指向子节点的指针数组 children。对于本题而言,数组长度为 26,即小写英文字母的数量。此时 children0 对应小写字母 a,children1 对应小写字母 b,...,children25 对应小写字母 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()
相关推荐
CoderIsArt4 小时前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
顶点多余5 小时前
那些在算法中适合巩固的知识点---1
java·前端·算法
罗西的思考7 小时前
【Agentic RL / 强化学习框架】Molt 设计解读
人工智能·算法·机器学习
hahaha60168 小时前
HLS高层次综合设计技巧--C++类和模板
图像处理·人工智能·算法·计算机视觉
多弗朗皮卡丘8 小时前
算法详解4:买卖股票的最佳时机系列(上)
算法
维克兜率天11 小时前
【维克】动量指标家族:RSI、ROC、CCI、Momentum全面解析
python·算法
AI情绪识别开源11 小时前
检信 AI 智能推广平台(代号:JX-Promote)
人工智能·算法·erlang
老当益壮梁奶奶12 小时前
Linux软件编程学习笔记(八):进程间通信详解(1)
linux·c语言·笔记·学习·算法
不会就选b12 小时前
算法日常・每日刷题--<BFS拓扑排序>4
算法
不正经学生12 小时前
C语言动态内存管理(上):堆上的自由与责任
c语言·开发语言·c++·算法·面试