# -*- coding:utf-8 -*-
# Author='长孤秋落' '2024/2/24'
# 博客:https://blog.csdn.net/weixin_36928396?type=blog
# may the odds be ever in your favor
"""
208. 实现 Trie (前缀树)
Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。
这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
请你实现 Trie 类:
Trie() 初始化前缀树对象。
void insert(String word) 向前缀树中插入字符串 word 。
boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
示例:
输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]
解释
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 True
trie.search("app"); // 返回 False
trie.startsWith("app"); // 返回 True
trie.insert("app");
trie.search("app"); // 返回 True
提示:
1 <= word.length, prefix.length <= 2000
word 和 prefix 仅由小写英文字母组成
insert、search 和 startsWith 调用次数 总计 不超过 3 * 104 次
"""
import CheckFuncPerf as cfp
from collections import defaultdict
class prenode:
def __init__(self):
self.chars = defaultdict(int)
class Trie_base:
def __init__(self):
self.node = prenode()
self.bEnd = False
def searchPrefix(self, prefix):
tmpNode = self
for achar in prefix:
ichar = ord(achar) - ord("a")
if tmpNode.node.chars[ichar] == 0:
return None
tmpNode = tmpNode.node.chars[ichar]
return tmpNode
def insert(self, word):
tmpNode = self
for achar in word:
ichar = ord(achar) - ord("a")
if tmpNode.node.chars[ichar] == 0:
tmpNode.node.chars[ichar] = Trie_base()
tmpNode = tmpNode.node.chars[ichar]
tmpNode.bEnd = True
def search(self, word):
node = self.searchPrefix(word)
return node is not None and node.bEnd
def startsWith(self, prefix):
return self.searchPrefix(prefix) is not None
class Trie_ext1:
def __init__(self):
self.data = [None] * 26
self.bEnd = False
def searchPrefix(self, prefix):
tmpnode = self
for achar in prefix:
ichar = ord(achar) - ord("a")
if not tmpnode.data[ichar]:
return None
tmpnode = tmpnode.data[ichar]
return tmpnode
def insert(self, word):
tmpnode = self
for achar in word:
ichar = ord(achar) - ord("a")
if not tmpnode.data[ichar]:
tmpnode.data[ichar] = Trie_ext1()
tmpnode = tmpnode.data[ichar]
tmpnode.bEnd = True
def search(self, word):
tmpnode = self.searchPrefix(word)
return tmpnode is not None and tmpnode.bEnd
def startsWith(self, prefix):
return self.searchPrefix(prefix) is not None
class Trie_ext2:
def __init__(self):
self.tree = {}
def insert(self, word):
tree = self.tree
for achar in word:
if achar not in tree:
tree[achar] = {}
tree = tree[achar]
tree["#"] = "#"
def search(self, word):
tree = self.tree
for achar in word:
if achar not in tree:
return False
tree = tree[achar]
return "#" in tree
def startsWith(self, prefix):
tree = self.tree
for achar in prefix:
if achar not in tree:
return False
tree = tree[achar]
return True
if __name__ == '__main__':
print('Hot54.py')
# 功能测试
# 超时测试
import random
from nltk.corpus import words
word_list = list(words.words())
def testTrie(aTrie, actions):
for act in actions:
if act[0]==1: # insert
aTrie.insert(act[1])
elif act[0]==2: # search
aTrie.search(act[1])
elif act[0]==3: # startsWith
aTrie.startsWith(act[1])
return 99
import random
actions = []
iLen = 1000
for iIdx in range(iLen):
actions.append([random.randint(1, 3), random.choice(word_list)])
tmpTrie = Trie_base()
result = cfp.getTimeMemoryStr(testTrie, tmpTrie, actions)
print(result['msg'], '执行结果 = {}'.format(result['result']))
tmpTrie = Trie_ext1()
result = cfp.getTimeMemoryStr(testTrie, tmpTrie, actions)
print(result['msg'], '执行结果 = {}'.format(result['result']))
tmpTrie = Trie_ext2()
result = cfp.getTimeMemoryStr(testTrie, tmpTrie, actions)
print(result['msg'], '执行结果 = {}'.format(result['result']))
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
力扣热题Python源代码 题目208. 实现 Trie (前缀树) Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。 这一数据结构有相当多的应用情景,例如自动补完和拼写检查。 请你实现 Trie 类: Trie() 初始化前缀树对象。 void insert(String word) 向前缀树中插入字符串 word 。 boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。 boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
资源推荐
资源详情
资源评论
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
收起资源包目录
![package](https://csdnimg.cn/release/downloadcmsfe/public/img/package.f3fc750b.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
共 2 条
- 1
资源评论
![avatar-default](https://csdnimg.cn/release/downloadcmsfe/public/img/lazyLogo2.1882d7f4.png)
![avatar](https://profile-avatar.csdnimg.cn/cbed55e440b64457b277d2d5c38e43aa_weixin_36928396.jpg!1)
![avatar-vip](https://csdnimg.cn/release/downloadcmsfe/public/img/user-vip.1c89f3c5.png)
长孤秋落
- 粉丝: 2211
- 资源: 27
上传资源 快速赚钱
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助
![voice](https://csdnimg.cn/release/downloadcmsfe/public/img/voice.245cc511.png)
![center-task](https://csdnimg.cn/release/downloadcmsfe/public/img/center-task.c2eda91a.png)
最新资源
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback-tip](https://img-home.csdnimg.cn/images/20220527035111.png)
安全验证
文档复制为VIP权益,开通VIP直接复制
![dialog-icon](https://csdnimg.cn/release/downloadcmsfe/public/img/green-success.6a4acb44.png)