实现说明
核心实现集中在 TrieNode、Trie和函数 dfs。
嵌套的两层循环是 for (const ch of word) { let next = node.children.get(ch); if (!next) { next = new TrieNode(); no… 和 for (const ch of prefix) { node = node.children.get(ch)!; if (!node) return []; }。
拿回来的是新对象,不是任何传入值的引用。
使用要点
- 守卫
!node一旦成立就走提前的return,把后续流程挡掉。
常见问题
dfs 会修改传入的参数吗?
不会。代码构造并返回新值,入参保持原样,对共享或冻结的数据结构调用是安全的。
这份代码可以原样复制进项目使用吗?
可以。粘进去就能运行,中间没有包管理器的事。 文件在加载时定义 dfs。
入口签名:const dfs = (n: TrieNode, path: string)
核心语句
return results.sort((a, b) => b.freq - a.freq).slice(0, limit).map(r => r.word);
for (const ch of prefix) { node = node.children.get(ch)!; if (!node) return []; }
const dfs = (n: TrieNode, path: string): void => {
if (n.isWord) results.push({ word: path, freq: n.freq });
for (const [ch, child] of n.children) dfs(child, path + ch);
};
代码示例
class TrieNode { children: Map<string, TrieNode> = new Map(); isWord = false; freq = 0; }
class Trie {
root = new TrieNode();
insert(word: string, freq = 1): void {
let node = this.root;
for (const ch of word) { let next = node.children.get(ch); if (!next) { next = new TrieNode(); node.children.set(ch, next); } node = next; }
node.isWord = true; node.freq += freq;
}
suggest(prefix: string, limit = 5): string[] {
let node = this.root;
for (const ch of prefix) { node = node.children.get(ch)!; if (!node) return []; }
const results: { word: string; freq: number }[] = [];
const dfs = (n: TrieNode, path: string): void => {
if (n.isWord) results.push({ word: path, freq: n.freq });
for (const [ch, child] of n.children) dfs(child, path + ch);
};
dfs(node, prefix);
return results.sort((a, b) => b.freq - a.freq).slice(0, limit).map(r => r.word);
}
}