第二十八天(字典树)
class TrieNode:
def __init__(self):
self.end=False # 表示是否存在某个结点
self.children=collections.defaultdict(TrieNode) # 儿子字典,所有键默认为TrieNode
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for s in word:
node = node.children[s] # node.children[s]默认为TrieNode,这里自动新建儿子
node.end = True
# print("insert " + word)
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.root
# print("search " + word)
for s in word:
node = node.children.get(s) # 获得键s,没有则返回None
if node is None: # 前缀匹配失败
return False
if node.end: # 该字符有结尾,即匹配成功
return True
else:
return False
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.root
for s in prefix:
node = node.children.get(s) # 获得键s,没有则返回None
if node is None: # 前缀匹配失败
return False
return True最后更新于