把 app 和 apple 放进普通字典能查整个单词,却不能直接看哪些单词从 app 开头。换个摆法,让以 a 开头的词从同一条边进来,这就是前缀树。
先插入 apple,查 app 这条路径当然走得通,但第三个字母还没标记为词尾。等单独插入 app,再查完整单词才会得到 True。
class Trie:
def __init__(self):
self.children = {}
self.end = False
def insert(self, word):
node = self
for ch in word:
if ch not in node.children:
node.children[ch] = Trie()
node = node.children[ch]
node.end = True
def _walk(self, text):
node = self
for ch in text:
node = node.children.get(ch)
if node is None:
return None
return node
def search(self, word):
node = self._walk(word)
return node is not None and node.end
def startsWith(self, prefix):
return self._walk(prefix) is not None
单次插入、查词、查前缀都是 O(L) 次字典访问,L 是本次字符串长度。空间与存下的不同前缀数成正比。布尔词尾标志独立保存,已有前缀无需重复建节点。

