初次接触字典树,什么是字典树呢?
字典树又被称为是前缀树。
如https://blog.csdn.net/weixin_39778570/article/details/81990417博客里,
从上图归纳出Trie树基本性质.
- 从根到某一个节点,拼接长字符串;
- 一个节点的子节点字符一定不相同;
- Trie提高效率,用空间换时间
数据结构常见的操作是:插入、查找、删除
对于字典树来说,删除我还不会。
插入字符串时,逐个字符对比,在python中用字典来保存节点,而且每个字符串都要有结束标记,如biac {"b":{"i":{"a":{"c:{"#":"#"}"}}}}。
查找字符串时,逐个字符对比,最后如果有结束标记,那么返回True,如果没有返回False。
代码如下:
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.lookup = {}
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
tree = self.lookup
for a in word:
if a not in tree:
tree[a] = {} #不断的在字典中添加节点,新节点都是以字典的形式内嵌进大字典的
tree = tree[a] #不断内嵌
# print(tree)
# 单词结束标志
tree["#"] = "#"
# print(self.lookup) #{'b': {'i': {'a': {'c': {'#': '#'}}}}}
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
tree = self.lookup
for a in word:
if a not in tree:
return False
tree = tree[a]
if "#" in tree:
return True
return False
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
tree = self.lookup
for a in prefix:
if a not in tree:
return False
tree = tree[a]
return True