← 中文资源

简体中文版本

Trie 前缀自动补全

把词表插入前缀树,按字典序枚举查询前缀的全部补全词,空前缀返回完整词表。

阅读英文原文

目标

构建 Trie 并支持前缀补全:返回所有以查询前缀开头的已插入单词,输出必须按字典序排列;空前缀表示遍历整棵树并返回全部词。

要点

节点保存子节点映射与词尾标记;补全时先逐字符下降,途中缺失子节点立即返回空;枚举用 DFS,遇到词尾就输出,再按键序递归,天然保证字典序。

提示

只在中层节点打词尾标记会丢失“某词是另一词前缀”的情形;收集后再排序不如遍历时按键序递归可靠。

验证

运行三个样例:空前缀返回全部排序词表,前缀恰好是完整单词时该词本身先于更长补全出现。 公开样例(与参考实现实测一致):

  • 输入 {"words":["tree","trie","try","trip","ten"],"prefix":"tr"},期望 {"matches":["tree","trie","trip","try"]}。
  • 输入 {"words":["a","ab","abc"],"prefix":""},期望 {"matches":["a","ab","abc"]}。
  • 输入 {"words":["cat","car","dog"],"prefix":"ca"},期望 {"matches":["car","cat"]}。

代码示例

class Trie {
  constructor() {
    this.root = { children: {}, end: false };
  }
  insert(word) {
    let node = this.root;
    for (const ch of word) {
      if (!node.children[ch]) node.children[ch] = { children: {}, end: false };
      node = node.children[ch];
    }
    node.end = true;
  }
  collect(node, prefix, out) {
    if (node.end) out.push(prefix);
    const keys = Object.keys(node.children).sort();
    for (const ch of keys) this.collect(node.children[ch], prefix + ch, out);
  }
  complete(prefix) {
    let node = this.root;
    for (const ch of prefix) {
      if (!node.children[ch]) return [];
      node = node.children[ch];
    }
    const out = [];
    this.collect(node, prefix, out);
    return out;
  }
}

const payload = JSON.parse(input);
const trie = new Trie();
for (const w of payload.words) trie.insert(w);
console.log(JSON.stringify({ matches: trie.complete(payload.prefix) }));