Trie
Weirane(讨论 | 贡献)2021年10月15日 (五) 21:20的版本 (建立内容为“Category:刷题 字典树。 <syntaxhighlight lang=python> class Trie: def __init__(self): self.children = defaultdict(Trie) self.isword…”的新页面)
字典树。
class Trie:
def __init__(self):
self.children = defaultdict(Trie)
self.isword = False
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
t = self
for c in word:
t = t.children[c]
t.isword = True
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
t = self
for c in word:
if c in t.children:
t = t.children[c]
else:
return False
return t.isword
def startsWith(self, prefix: str) -> bool:
"""Returns if there is any word in the trie that starts with the given prefix."""
t = self
for c in prefix:
if c in t.children:
t = t.children[c]
else:
return False
return True