python利用字典结构的简便版本(注意看注释理解)
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.lookup = {} #构建一个字典结构,用于存储元素数据
def insert(self, word):
"""
Inserts a word into the trie.
"""
tree = self.lookup #给公共字典取别名
for a in word:
if a not in tree:
tree[a] = {} #逐元素提取字母到字典中查找是否存在,如果不存在就在字典内建立一个空的子字典
tree = tree[a] #跟踪标记位置变换,进入到字字典中进行操作
# 单词结束标志
tree["#"] = "#" #插入单词结束在最后一个字字典中插入结束符
print(self.lookup)
def search(self, word):
"""
Returns if the word is in the trie.
"""
tree = self.lookup
for a in word:
if a not in tree: #{u'a': {u'p': {u'p': {'#': '#', u'l': {u'e': {'#': '#'}}}}}}
return False #层层深入子字典查找元素,形如上面结构,apple和app可以同时存在只不过在第二个p字母之后有了两个分支,可以结束也可以继续下一个字母l
tree = tree[a] #跟踪标记变换
if "#" in tree: #当遍历到最后一个匹配字母后,如果最后一个子字典中有#结束符标志那么代表存在该单词,如果没有那么就是现存单词还要更长,所以搜索失败
return True
return False
def startsWith(self, prefix):
"""
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 #缩减版的search操作,不用判断是否有结束,有前缀即可
tree = tree[a]
return True