题目
实现 Trie 类,包含 insert(word)、contains(word) 和 count_prefix(prefix) 三个方法。单词必须是非空的小写字母字符串,重复插入同一个单词应被忽略,避免重复计数。contains 判断某个完整单词是否存在;count_prefix 返回以给定前缀开头的不同已插入单词数量,如果前缀本身也是完整单词也要计入。
- 输入:待插入的小写单词列表和待查询的小写前缀列表。
- 输出:按查询顺序排列的前缀计数列表。
解题思路
每个节点保存子节点字典、经过该节点的单词数量 count,以及标记单词结尾的 terminal 布尔值。插入新单词时,根节点计数加一,随后沿每个字符向下走,经过的每个节点计数都加一,最后一个节点标记为终止。为了识别重复单词,额外维护一个集合,已存在的单词直接返回,不再修改计数。
contains 沿字符路径前进,若中途缺少子节点返回 False,否则返回末节点的 terminal 标志。count_prefix 同样沿路径前进,缺节点返回 0,否则返回该节点的 count。两个查询的复杂度都只与字符串长度有关,与已存单词数量无关。前缀计数依赖节点上的累计值,因此即使前缀本身不是完整单词也能得到正确结果。
参考实现要点
- TrieNode 使用 slots 减少内存,并保存 children、count、terminal。
- insert 校验非空、全小写字母;重复单词通过集合直接忽略。
- 根节点 count 加一,然后逐字符创建或复用节点并累加 count。
- 末尾节点设置 terminal=True,contains 依赖该标志判断整词。
- count_prefix 在路径中断时返回 0,否则返回目标节点的 count。
常见错误
- 只统计 terminal 节点,导致不是完整单词的前缀被计为 0。
- 重复插入同一个单词时继续累加计数,前缀结果偏大。
- 使用 word.isalpha() 但忘记 word.islower(),大写单词被接受。
- 查询空前缀时直接返回 0,而正确语义应是全部单词数量。
验证方式
运行两个公开样例,确认分别得到 [3, 2, 0] 和 [2, 2]。再测试空前缀、比所有单词都长的前缀、单字符单词、完全没有公共前缀的单词,以及空串、大写、包含连字符等非法输入。最后检查第一个样例中 contains(“app”) 为 True,而 contains(“ap”) 为 False,确认整词与前缀语义没有混淆。
代码示例
class TrieNode:
__slots__ = ("children", "count", "terminal")
def __init__(self):
self.children = {}
self.count = 0
self.terminal = False
class Trie:
def __init__(self):
self.root = TrieNode()
self._words = set()
def insert(self, word):
if not word or not word.isalpha() or not word.islower():
raise ValueError("words must be non-empty lowercase letters")
if word in self._words:
return
self._words.add(word)
node = self.root
node.count += 1
for char in word:
node = node.children.setdefault(char, TrieNode())
node.count += 1
node.terminal = True
def contains(self, word):
node = self.root
for char in word:
node = node.children.get(char)
if node is None:
return False
return node.terminal
def count_prefix(self, prefix):
node = self.root
for char in prefix:
node = node.children.get(char)
if node is None:
return 0
return node.count
if __name__ == "__main__":
trie = Trie()
for word in ["apple", "app", "apply"]:
trie.insert(word)
print([trie.count_prefix(prefix) for prefix in ["app", "appl", "b"]])