当前位置: 首页 > news >正文

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

解法一:字典树

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

  • 指向子节点的指针数组 children。对于本题而言,数组长度为 26,即小写英文字母的数量。此时 children[0] 对应小写字母 a,children[1] 对应小写字母 b,…,children[25] 对应小写字母 z。
  • 布尔字段 isEnd,表示该节点是否为字符串的结尾。
    在这里插入图片描述
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时(说明有相同前缀),才新建nodenode.children[num] = new Trie()
  • Trie node = this,而不是Trie node = new Trie()
http://www.dtcms.com/a/79514.html

相关文章:

  • 从 0 到 1,AgenticOps 如何打造企业级 AI 生产力?
  • 详解如何通过Python的BeautifulSoup爬虫+NLP标签提取+Dijkstra规划路径和KMeans聚类分析帮助用户规划旅行路线
  • 软件工程之软件验证计划Software Verification Plan
  • set容器详细解释
  • 嵌入式硬件篇---蓝牙模块
  • Node.js技术原理分析系列6——基于 V8 封装一个自己的 JavaScript 运行时
  • Java的输入
  • Tr0ll2靶机详解
  • matlab的s-function模块使用说明
  • Vulhub-wordpress通关攻略
  • 【LangChain入门 6 Chain组件】单链和多链
  • 微信小程序的业务域名配置(通过ingress网关的注解)
  • Java 中处理邮件附件:本地文件 vs 在线 URL
  • 产业观察:ASML2025.3.21
  • Git(12)GitLab持续集成(CICD)
  • 用ArcGIS做一张符合环评要求的植被类型图
  • [过程记录] 《分寝室》 一题做法思考
  • 基于springboot的教务系统(源码+lw+部署文档+讲解),源码可白嫖!
  • 《模型思维》第二十三章 “与集体行动有关的问题” 总结
  • LLM之向量数据库Chroma milvus FAISS
  • AI+视频赋能智慧农业:EasyCVR打造全域可视化农场监管平台
  • AI日报 - 2025年3月20日
  • 《Java核心三问:字符串、equals()、hashCode()的隐藏雷区与完美避坑手册》
  • UltraSearch一键直达文件,高效搜索新体验
  • 双指针算法-day14(分组循环)
  • java数据结构之双端对列
  • 力扣刷题——25.K个一组翻转链表
  • 【全国产化主板】解决方案探讨:CPU、FPGA、GPU、AI的融合与优化
  • 【最后203篇系列】020 rocksdb agent
  • 《视觉SLAM十四讲》ch13 设计SLAM系统 相机轨迹实现