字典树的python实现
# coding:utf-8
class Trie(object):
"""字典树的删改查"""
def __init__(self):
self.lookup = {}
def insert(self, word: str) -> None:
tree = self.lookup
for a in word:
if a not in tree:
tree[a] = {}
tree = tree[a]
tree['#'] = '#'
def search(self, word: str) -> bool:
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:
tree = self.lookup
for a in prefix:
if a not in tree:
return False
tree = tree[a]
return True
@property
def content(self):
return self.lookup
if __name__ == '__main__':
trie = Trie()
trie.insert("你好吗")
trie.insert("我好呀")
trie.insert("你好吗,我是新来的")
print(trie.content)
print(trie.search("你好吗"))
print(trie.startsWith("我是"))
print(trie.startsWith("你"))
trie.PNG
网友评论