当前位置: 首页 > 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 而不是newfor(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()

http://www.mrgr.cn/news/95309.html

相关文章:

  • 从零实现本地文生图部署(Stable Diffusion)
  • fontTools工具的使用介绍
  • 算法刷题记录——LeetCode篇(6) [第501~600题](持续更新)
  • Powershell WSL部署ubuntu22.04.5子系统
  • The Illustrated Stable Diffusion
  • A l密码学(Deepseek)
  • 内网渗透(CSMSF) 构建内网代理的全面指南:Cobalt Strike 与 Metasploit Framework 深度解析
  • 增加对路由参数的支持
  • 单台openEuler24.03 LTS下的开源大数据环境搭建
  • 2025年优化算法:龙卷风优化算法(Tornado optimizer with Coriolis force,TOC)
  • 高级java每日一道面试题-2025年3月07日-微服务篇[Eureka篇]-Eureka Server和Eureka Client关系?
  • Docker和Dify学习笔记
  • 详细介绍VUE,带你了解VUE!!!
  • AI对话框实现
  • HarmonyOS开发,A持有B,B引用A的场景会不会导致内存泄漏,看这里!
  • 电机控制常见面试问题(十四)
  • 软件设计师笔记持续更新-看学以致知视频笔记
  • 前后端项目
  • Django之旅:第三节--templates模版的使用
  • 在 Spring Boot 中调用 AnythingLLM 的发消息接口