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

一种字典树的Python实现

字典树,也叫单词查找树,Trie, 是一种自定义的树形数据结构,用于统计、排序和保存大量的字符串,利用字符串的公共前缀来减少查询时间和存储空间,查找效率比哈希树高。
字典树应该支持的操作:插入 查找 前缀 移除 展示:
insert(word): Insert a word into the Trie
search(word): Return if the word in the Trie
startsWith(prefix): Return if there is any words in the trie that starts with the given prefix
remove(word): Remove word from the Trie
show(): Print the architecture of the Trie using indents

Python实现

class Trie:def __init__(self):"""Initialize your data structure here."""self.dic = {}def insert(self, word: str) -> None:"""Inserts a word into the trie."""tree = self.dicfor i in word:tree = tree.setdefault(i, {})tree['#'] = '#'def search(self, word: str) -> bool:"""Returns if the word is in the trie."""tree = self.dicfor i in word:if i not in tree:return Falsetree = tree[i]return '#' in treedef startsWith(self, prefix: str) -> bool:"""Returns if there is any word in the trie that starts with the given prefix."""tree = self.dicfor i in prefix:if i not in tree:return Falsetree = tree[i]return Truedef remove(self, word: str) -> None:"""Remove the word from the Trie."""def _remove_helper(node, word, index):if index == len(word):# 找到单词末尾,删除结束标记if '#' in node:del node['#']return len(node) == 0  # 如果节点没有其他子节点,可以删除char = word[index]if char not in node:return False  # 单词不存在should_delete = _remove_helper(node[char], word, index + 1)if should_delete:del node[char]return len(node) == 0  # 检查当前节点是否可以删除_remove_helper(self.dic, word, 0)def show(self):"""以缩进形式层次化展示Trie树结构"""def _show_helper(node, level=0):for key, child in node.items():if key == '#':print('  ' * level + '# (end)')else:print('  ' * level + key)_show_helper(child, level + 1)_show_helper(self.dic)
http://www.xdnf.cn/news/9685.html

相关文章:

  • 什么是数字化转型,如何系统性重构业务逻辑
  • Android 构建系统中常见的 .mk 文件及其作用
  • 涨薪技术|0到1学会性能测试第88课-Web_service_call函数
  • Spring AI Alibaba 发布企业级 MCP 分布式部署方案
  • LeetCode 169:多数元素 - 摩尔投票法的精妙解法
  • 【freertos-kernel】queue(发送)
  • # Python 语音助手本地的ollama实现
  • nt!MmMapViewInSystemCache函数分析PointerPte的填充
  • AD/DA HAL库API
  • 内容中台的构建基础是什么?
  • King3399(ubuntu文件系统)iic(i2c)功能测试
  • MP4视频文件播放Demo(附源码)
  • 头歌之动手学人工智能-Pytorch 之autograd
  • 算法 Arrays.sort()函数自定义排序(Comparator 接口)
  • [网页五子棋][匹配模块]服务器开发、用户管理器(创建匹配请求/响应对象、处理连接成功、处理下线)
  • 根据jvm源码剖析类加载机制
  • Python爬虫实战:研究Tornado框架相关技术
  • [Vue组件]半环进度显示器
  • 小猴子摆玩具
  • 计算机网络第一章计算机网络概述(竟成)
  • 小白成长之路-Linux操作系统-进程管理
  • 【机器人编程基础】python中的常用数据类型
  • ElasticSearch查询指定时间内出现的次数/2秒内出现的次数
  • 我们来学mysql -- 输出一份“数据备份还原”sh脚本
  • 手写字魔法消除1:数据集说明(含下载链接)
  • Kruskal算法剖析与py/cpp/Java语言实现
  • linux中基础IO(上)
  • 浅谈 JavaScript 性能优化
  • 深度解析 Nginx 配置:从性能优化到 HTTPS 安全实践
  • YOLOv8性能提升:引入华为GhostNetv1特征提取网络