何时使用
- 大量字符串反复按前缀查询:"是否存在以 p 开头的词""以 p 开头的词有几个 / 值之和"
- 词典 + 文本:词根替换、最短 / 最长前缀匹配、自动补全
- 查询中带通配符
.:在 Trie 上 DFS
- 网格或文本里同时找很多个单词:单词建 Trie,搜索时与 Trie 同步往下走并剪枝
- 只查完整单词、没有前缀需求时,哈希集合通常更简单
模板 1:基础 Trie(insert / walk)
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = True
def walk(self, s):
node = self.root
for ch in s:
node = node.children.get(ch)
if node is None:
return None
return node
class TrieNode {
constructor() {
this.children = new Map();
this.isEnd = false;
}
}
class Trie {
constructor() { this.root = new TrieNode(); }
insert(word) {
let node = this.root;
for (const ch of word) {
if (!node.children.has(ch)) node.children.set(ch, new TrieNode());
node = node.children.get(ch);
}
node.isEnd = true;
}
walk(s) {
let node = this.root;
for (const ch of s) {
node = node.children.get(ch);
if (!node) return null;
}
return node;
}
}
search(w) = walk(w) 非空且 is_end;startsWith(p) = walk(p) 非空
- 节点上存前缀聚合值时,同一个键重复插入要按"覆盖"处理:路径上加新旧值之差