python数据结构前缀树+贪心算法-左程云视频学习笔记-更新中
2023-09-27 14:29:29 时间
前缀树
可以快读知道有多少以某个字符串作为前缀O(m)
可以快速知道有没有某个字符串O(m)
点的数据结构
class TrieNode():
def __init__(self):
self.pas = 0 # 通过了多少次,沿途pas加加
self.end = 0 # 是否是尾结点,值表示几个结尾,末尾end++
self.nexts = [None] * 26 # i位表示有没有去i位的路
实现代码
class Trie():
root = TrieNode() # 头结点
# 插入结点方法
def insert(self,word):
if word == None:
return
node = self.root # 从根结点出发
node.pas += 1
for s in word:
index = ord(s) - 97 # 减字符a的asc码值
if node.nexts[index] == None:
node.nexts[index] = TrieNode()
node = node.nexts[index]
node.pas += 1 # 沿途pas++
node.end += 1 # 最后end++
# 结点查询,查询字符串加入过几次
def search(self,word):
if word == None:
return
node = self.root # 根结点出发
for s in word: # word遍历一遍
index = ord(s) - 97
if node.nexts[index] == None: # 只要没路了,直接返回0
return 0
node = node.nexts[index]
return node.end
# 加入的字符串中,有几个是以某字符串作为前缀的
def prefixNumber(self,pre):
if pre == None:
return 0
node = self.root
for s in pre:
index = ord(s) - 97
if node.nexts[index] == None:
return 0
node = node.nexts[index]
return node.pas # 返回结果的pas值
# 删除加入的某个字符串
def delete(self,word):
if self.search(word) == 0: # 如果没有加入过这个字符串,则不存在删除
return
node = self.root
node.pas -= 1
for s in word:
index = ord(s) - 97
node.nexts[index].pas -= 1
if node.nexts[index].pas == 0: # 下级结点减到0之后,就可以直接放弃了
node.nexts[index] = None
return
node = node.nexts[index]
node.end -= 1 # 最后一个结点end--
贪心算法
相关文章
- python排序算法——希尔排序(附代码)
- 跟我学Python图像处理丨掌握4种图像平滑算法
- python并发编程之协程
- python机器学习——朴素贝叶斯算法笔记详细记录
- Python推荐算法:LFM梯度下降算法实现
- 字母算术的python算法
- Python数据分析师需要学什么
- Python初学者为什么要选择Jupyter?
- 机器学习笔记之python实现支持向量机SVM算法样例
- Python Web学习笔记之图解TCP/IP协议和浅析算法
- python 数组的操作--统计某个元素在列表中出现的次数
- PyQt(Python+Qt)学习随笔:QTabWidget部件选项卡可用状态访问方法isTabEnabled、setTabEnabled
- PyQt(Python+Qt)学习随笔:QTabWidget选项卡部件概述和属性介绍
- PyQt(Python+Qt)学习随笔:QTreeWidget树型部件中的QTreeWidgetItem项构造方法
- Python 数据库连接池DBUtils
- python 算法学习部分代码记录篇章1
- 好学编程:Python有哪些优势和用途?学Python就业方向有哪些?
- Python PCA主成分分析算法
- Python 模块浅析
- Python-算法基础
- python、java实现二叉树,细说二叉树添加节点、深度优先(先序、中序、后续)遍历 、广度优先 遍历算法