前缀树实际上是一颗 N 叉树......又因为用字典的形式来存储每个节点,所以也叫字典树。
本质上为字典的多重嵌套。
class Trie:
def __init__(self):
self.root = {}
def insert(self, word: str) -> None:
cur = self.root
for w in word:
if w not in cur:
cur[w] = {}
cur = cur[w]
cur['#'] = {}
def search(self, word: str) -> bool:
cur = self.root
for w in word:
if w in cur:
cur = cur[w]
else:
return False
return '#' in cur
def startsWith(self, prefix: str) -> bool:
cur = self.root
for p in prefix:
if p in cur:
cur = cur[p]
else:
return False
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)