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

数据结构 - 字典树 Trie

字典树(Trie)是一种树形数据结构,主要用于高效地存储和检索字符串集合。它通过利用字符串的公共前缀来节省存储空间,常用于词典查询、自动补全等场景。

1. 什么是字典树

字典树的每条边代表一个字符,从根节点到某一节点的路径表示一个字符串。如果某节点被标记为结束节点,则表示该路径对应的字符串存在于集合中。

2. 字典树的基本操作

字典树的核心操作包括插入和查找,时间复杂度通常为字符串长度的线性级别,比暴力搜索更高效。

2.1 树的构造

对于每个树的节点,应该包含以下字段:

  • 指向子节点的数组 children,数组长度为所有字符的数量;
  • 一个布尔变量 end,用于指定是否为字符串结尾。
2.2 插入节点
void insert(std::string word) {Trie *node = this;for (char c : word) {c -= 'a';if (node->children[c] == nullptr) {node->children[c] = new Trie();}node = node->children[c];}node->end = true;
}
2.3 查询
bool searchPrefix(std::string prefix) {Trie *node = this;for (char c : prefix) {c -= 'a';if (node->children[c] == nullptr) {return false;}node = node->children[c];}return node != nullptr && node->end;
}
2.4 代码模版
class Trie {
public:void insert(std::string word) {Trie *node = this;for (char c : word) {c -= 'a';if (node->children[c] == nullptr) {node->children[c] = new Trie();}node = node->children[c];}node->end = true;}bool searchPrefix(std::string prefix) {Trie *node = this;for (char c : prefix) {c -= 'a';if (node->children[c] == nullptr) {return false;}node = node->children[c];}return node != nullptr && node->end;}private:std::vector<Trie*> children;bool end;
};

3. 示例

208. 实现 Trie (前缀树)

http://www.zskr.cn/news/15810.html

相关文章:

  • 激活函数实现
  • win10界面如何改成经典菜单?
  • 量子迁移计划启动:应对未来密码学挑战
  • 珂朵莉树 ODT
  • 01.linux基础
  • 详细介绍:Kubernetes实战:MariaDB误删恢复与数据持久化
  • 从模拟入侵到渗透测试:我摸清了黑客的套路,也懂了企业的软肋 - 详解
  • 集合幂级数,FMT 与 FWT 学习笔记
  • 上传文件前端需要注意的三个点:
  • Jenkins安装与配备
  • 适合新手的PPT模板网站,简单操作但效果好!
  • 无人机常用的几种飞行模式
  • springCloudMaven打包配置 - br
  • 题解:P5504 [JSOI2011] 柠檬
  • 太简单了!原来PS在线抠图可以这么玩,背景分离无压力
  • 深入解析:【Leetcode】随笔
  • DateStyle日期时间字符串序列化 - br
  • 十月四日就听《10월 4일》
  • 赋能制造新质生产力:制造业专用低代码平台选型指南(2025) - 详解
  • 4-7〔O҉S҉C҉P҉ ◈ 研记〕❘ WEB应用攻击▸文件上传漏洞-B - 实践
  • 完整教程:六款智能证照工具盘点,打造个性化“数字身份档案”
  • 深入解析:音频降噪技术:从原理到工具的完整指南(scipy librosa noisereduce soundfile pedalboard)
  • zkSync Era在ETHDenver的技术盛宴:zkEVM与Layer2创新实践
  • 11_linux镜像下载
  • 10_windows11安装virtualbox
  • OpenEuler 25.03 installed UKUI but cant run msedge and chrome
  • 网络调整config.xml的android.mk解析
  • 【Rive】rive-android源码分析
  • 完整教程:基于Spring Boot的爱琴海购物公园网上商城系统的设计与实现
  • 6_什么是知识图谱