AI 代码审查实战:用 JavaScript 回文树维护不同回文与频次快照

10-19 4阅读

让 AI 写一个回文函数,通常很快就能得到中心扩展或 Manacher。真正需要审查的另一类需求是:文本不断从右侧追加,希望随时知道已经出现多少种不同回文,并在某个时刻导出每种回文的出现次数。这里的核心对象是回文内容的身份。相同内容即使出现在多个位置,也应当落在同一个节点;位置不同带来的重复则进入频次统计。

本文把接口限定为追加型 Unicode 码点流,使用 JavaScript 实现回文树 Eertree。九段程序都能单独保存成 .cjs 文件运行,已在 Node.js v24.19.0 执行。为了让复制测试不依赖隐藏文件,涉及完整数据结构的示例会重复给出类定义。代码适合学习、审查和小规模验证;接入服务时还要补充输入配额、内存监控及封装。

AI 代码审查实战:用 JavaScript 回文树维护不同回文与频次快照
AI 生成概念配图:符号流、共享节点与计数汇聚的视觉隐喻,不是可执行流程图或精确的回文树结构图。

一、先固定字符单位和计数口径

本文只统计非空、连续、按码点精确相等的回文子串,允许出现位置相互重叠。例如 aaaa 有四种回文内容,而各自出现次数分别为四、三、二、一。不同回文数与全部出现次数是两个问题,不能把一个 Set 的大小同时当作两者。空串对应算法中的辅助根,但不进入业务结果。

JavaScript 字符串的 length 和下标使用 UTF-16 码元。按照 ECMAScript 的字符串迭代规范,for...of 按码点迭代;配对代理项会作为一个字符串值产出。本文额外通过 isWellFormed 拒绝孤立代理项,因此输入符号严格限制为 Unicode 标量值。组合附加符、变体选择符和零宽连接符仍然是单独的码点,不能把这一实现宣传成字素簇级回文识别。

规范化也属于接口语义。本文不会自动执行 NFC、大小写折叠或忽略空白。调用方若需要这些规则,应当先明确转换后的序列才是统计对象,并接受原文位置映射需要额外维护的事实。把清洗步骤偷偷塞进算法,会让审查者无法解释一个节点究竟对应哪段原始文本。

独立示例 1,保存为 example-01.cjs 后运行 node example-01.cjs:

"use strict";
const assert = require("node:assert/strict");
const text = "😀a😀";
assert.equal(text.length, 5);
assert.deepEqual([...text], ["😀", "a", "😀"]);
assert.equal("e\u0301".length, 2);
assert.equal([..."e\u0301"].length, 2);
assert.equal("\uD83D".isWellFormed(), false);
console.log(JSON.stringify({ utf16: text.length, codePoints: [...text].length,
  combinedCodePoints: [..."e\u0301"].length }));

输出:

{"utf16":5,"codePoints":3,"combinedCodePoints":2}

二、先写不共享思路的慢参考

AI 生成的实现即使自带测试,也可能让测试复用同一段错误的后缀逻辑。这里先枚举所有半开区间,再用两端比较判断回文,最后按完整内容累计次数。这份参考没有节点、转移边或后缀链接,与被测算法的推导路线不同,适合为短串提供独立答案。

这段参考的时间上界为立方级,还会创建子串;它只用于测试,不能替代上线实现。特别要保留重叠区间,否则 aba 在 ababa 中第二次出现会被漏掉。输出排序只为断言稳定,采用 JavaScript 字符串比较顺序,不声称这就是 Unicode 码点顺序或中文词典顺序。

独立示例 2,保存为 example-02.cjs 后运行 node example-02.cjs:

"use strict";
const assert = require("node:assert/strict");
function naive(text) {
  const a = [...text], counts = new Map();
  for (let start = 0; start < a.length; start++) {
    for (let end = start + 1; end <= a.length; end++) {
      let ok = true;
      for (let l = start, r = end - 1; l < r; l++, r--) {
        if (a[l] !== a[r]) { ok = false; break; }
      }
      if (ok) {
        const key = a.slice(start, end).join("");
        counts.set(key, (counts.get(key) ?? 0) + 1);
      }
    }
  }
  return counts;
}
const counts = naive("ababa");
assert.equal(counts.get("a"), 3);
assert.equal(counts.get("aba"), 2);
assert.equal(counts.size, 5);
console.log(JSON.stringify([...counts].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));

输出:

[["a",3],["aba",2],["ababa",1],["b",2],["bab",1]]

三、节点代表内容,追加只更新最长回文后缀

Rubinchik 与 Shur 的 Eertree 原始论文给出了按不同回文建立节点、用后缀链接支持在线追加的结构。它包含长度为负一和零的两个辅助根;每次追加最多引入一个新回文。本文采用数组编号零和一存放这两个根,真实节点从二开始,因此 distinct 等于节点总数减二。

审查实现时可以盯住一个具体下标。追加的符号位于 p,候选回文长度为 length,它左边的待匹配位置就是 p - 1 - length。匹配失败便沿 link 缩短候选;负一根使这个位置恰好回到 p,提供确定的终止点。当前符号必须先放入 symbols,否则这个边界技巧失去成立条件。

next 的键是外包的那个符号。例如从 aba 经字符 c 转移,代表 cabac。只有找不到既有转移时才创建节点,不能每次遇到回文都新建一份。last 表示当前整个前缀的最长回文后缀,并非历史最长回文;把这两个概念混用,下一次追加就可能从错误的位置开始寻找。

下面类中的 nodes 和 symbols 为了审查而公开。示例不会直接修改它们;生产接口宜改为私有状态,只暴露只读诊断。text 使用首次出现的结束下标重建内容,不在每个节点里常驻一份完整字符串。append 的返回值给出节点身份和是否新建,适合用于驱动增量界面。

独立示例 3,保存为 example-03.cjs 后运行 node example-03.cjs:

"use strict";
class Eertree {
  constructor() {
    this.symbols = [];
    this.nodes = [
      { length: -1, link: 0, next: new Map(), raw: 0, end: -1 },
      { length: 0, link: 0, next: new Map(), raw: 0, end: -1 }
    ];
    this.last = 1;
  }
  get distinct() { return this.nodes.length - 2; }
  findExtendable(v, c) {
    const p = this.symbols.length - 1;
    for (;;) {
      const left = p - 1 - this.nodes[v].length;
      if (left >= 0 && this.symbols[left] === c) return v;
      v = this.nodes[v].link;
    }
  }
  append(c) {
    if (typeof c !== "string" || !c.isWellFormed() || [...c].length !== 1) {
      throw new TypeError("one Unicode scalar value required");
    }
    this.symbols.push(c);
    const parent = this.findExtendable(this.last, c);
    let id = this.nodes[parent].next.get(c);
    const created = id === undefined;
    if (created) {
      const length = this.nodes[parent].length + 2;
      let link = 1;
      if (length > 1) {
        const q = this.findExtendable(this.nodes[parent].link, c);
        link = this.nodes[q].next.get(c);
      }
      id = this.nodes.length;
      this.nodes.push({ length, link, next: new Map(), raw: 0,
        end: this.symbols.length - 1 });
      this.nodes[parent].next.set(c, id);
    }
    this.last = id;
    this.nodes[id].raw++;
    return { id, created, distinct: this.distinct };
  }
  appendText(text) {
    if (typeof text !== "string" || !text.isWellFormed()) {
      throw new TypeError("well-formed string required");
    }
    for (const c of text) this.append(c);
    return this;
  }
  snapshot() {
    const counts = this.nodes.map(n => n.raw);
    for (let id = this.nodes.length - 1; id >= 2; id--) {
      counts[this.nodes[id].link] += counts[id];
    }
    return this.nodes.slice(2).map((n, i) => ({
      id: i + 2, length: n.length, firstEnd: n.end,
      occurrences: counts[i + 2]
    }));
  }
  text(id) {
    if (!Number.isInteger(id) || id < 2 || id >= this.nodes.length) {
      throw new RangeError("non-root node id required");
    }
    const n = this.nodes[id];
    return this.symbols.slice(n.end - n.length + 1, n.end + 1).join("");
  }
}
const assert = require("node:assert/strict");
const tree = new Eertree();
const events = [..."ababa"].map(c => tree.append(c));
assert.deepEqual(events.map(e => e.distinct), [1, 2, 3, 4, 5]);
assert.equal(tree.text(tree.last), "ababa");
const aId = tree.nodes[0].next.get("a");
const event = tree.append("c");
assert.equal(tree.nodes[0].next.get("a"), aId);
assert.equal(event.distinct, 6);
console.log(JSON.stringify(events.map(e => [e.id, e.created, e.distinct])));

输出:

[[2,true,1],[3,true,2],[4,true,3],[5,true,4],[6,true,5]]

四、后缀链接必须指向最长真回文后缀

一个看起来能跑的实现,可能把新节点的 link 直接设成扩展父节点。这两个关系服务于不同问题:扩展父节点移走首尾字符,后缀链接移走前面的一段。例如 ababa 的扩展父节点是 bab,因为首尾各去掉一个 a 后剩下 bab;它的最长真回文后缀则是 aba。这两个节点长度相同,内容却不同,仅仅比较长度看不出错误。

创建长度大于一的节点时,代码从扩展父节点的 link 开始继续寻找能被当前符号包住的候选,再读取相应转移。正确目标已经出现过,所以链接目标编号小于新节点编号。这个不变量后来会用于倒序传播频次。它成立的前提是节点只追加、从不重排;若为了显示排序而原地重排 nodes,整套编号关系都会被破坏。

示例四逐个重建节点文本,并通过枚举所有真后缀寻找最长回文后缀,验证链接确实符合含义。长度严格下降、编号严格变小只是必要条件;一条指向过短回文的链接也可能满足这两条,因此还需要内容级核对。根节点的内部长度不必与对外展示的空字符串混淆。

独立示例 4,保存为 example-04.cjs 后运行 node example-04.cjs:

"use strict";
class Eertree {
  constructor() {
    this.symbols = [];
    this.nodes = [
      { length: -1, link: 0, next: new Map(), raw: 0, end: -1 },
      { length: 0, link: 0, next: new Map(), raw: 0, end: -1 }
    ];
    this.last = 1;
  }
  get distinct() { return this.nodes.length - 2; }
  findExtendable(v, c) {
    const p = this.symbols.length - 1;
    for (;;) {
      const left = p - 1 - this.nodes[v].length;
      if (left >= 0 && this.symbols[left] === c) return v;
      v = this.nodes[v].link;
    }
  }
  append(c) {
    if (typeof c !== "string" || !c.isWellFormed() || [...c].length !== 1) {
      throw new TypeError("one Unicode scalar value required");
    }
    this.symbols.push(c);
    const parent = this.findExtendable(this.last, c);
    let id = this.nodes[parent].next.get(c);
    const created = id === undefined;
    if (created) {
      const length = this.nodes[parent].length + 2;
      let link = 1;
      if (length > 1) {
        const q = this.findExtendable(this.nodes[parent].link, c);
        link = this.nodes[q].next.get(c);
      }
      id = this.nodes.length;
      this.nodes.push({ length, link, next: new Map(), raw: 0,
        end: this.symbols.length - 1 });
      this.nodes[parent].next.set(c, id);
    }
    this.last = id;
    this.nodes[id].raw++;
    return { id, created, distinct: this.distinct };
  }
  appendText(text) {
    if (typeof text !== "string" || !text.isWellFormed()) {
      throw new TypeError("well-formed string required");
    }
    for (const c of text) this.append(c);
    return this;
  }
  snapshot() {
    const counts = this.nodes.map(n => n.raw);
    for (let id = this.nodes.length - 1; id >= 2; id--) {
      counts[this.nodes[id].link] += counts[id];
    }
    return this.nodes.slice(2).map((n, i) => ({
      id: i + 2, length: n.length, firstEnd: n.end,
      occurrences: counts[i + 2]
    }));
  }
  text(id) {
    if (!Number.isInteger(id) || id < 2 || id >= this.nodes.length) {
      throw new RangeError("non-root node id required");
    }
    const n = this.nodes[id];
    return this.symbols.slice(n.end - n.length + 1, n.end + 1).join("");
  }
}
const assert = require("node:assert/strict");
const tree = new Eertree().appendText("ababa");
const label = id => id < 2 ? "" : tree.text(id);
const links = tree.nodes.slice(2).map((n, i) => {
  const id = i + 2;
  assert.ok(n.link < id);
  assert.ok(tree.nodes[n.link].length < n.length);
  const word = [...tree.text(id)];
  let expected = "";
  for (let k = 1; k < word.length; k++) {
    const tail = word.slice(k);
    if (tail.every((c, j) => c === tail[tail.length - 1 - j])) {
      expected = tail.join(""); break;
    }
  }
  assert.equal(label(n.link), expected);
  return [label(id), label(n.link)];
});
console.log(JSON.stringify(links));

输出:

[["a",""],["b",""],["aba","a"],["bab","b"],["ababa","aba"]]

五、把原始命中次数和汇总次数分开

每次 append 只给 last 的 raw 加一。raw 的含义是这个节点被选作某个前缀最长回文后缀的次数。以 aaaa 为例,每一步分别命中 a、aa、aaa、aaaa,所以四个 raw 都为一。直接把 raw 展示为出现次数,会漏掉较长回文内部结束于同一位置的短回文。

snapshot 先复制 raw,再沿后缀链接把计数从晚创建的节点传给早创建的节点。对于每个结束位置,最长回文后缀及其链接链恰好覆盖该位置结束的全部非空回文,因此传播后得到每个内容的总出现次数。辅助根虽然会收到数值,但没有业务含义,也不会导出。

最容易隐藏的错误是把传播结果写回 raw。这样第一次导出看似正确,第二次导出又会把已经汇总过的次数传播一遍。给方法起名 finalize 并不能消除这个问题;除非接口明确封闭对象且禁止再次调用,否则应当使查询本身无副作用。本文选择每次从原始命中重新计算,保留继续追加的能力。

独立示例 5,保存为 example-05.cjs 后运行 node example-05.cjs:

"use strict";
class Eertree {
  constructor() {
    this.symbols = [];
    this.nodes = [
      { length: -1, link: 0, next: new Map(), raw: 0, end: -1 },
      { length: 0, link: 0, next: new Map(), raw: 0, end: -1 }
    ];
    this.last = 1;
  }
  get distinct() { return this.nodes.length - 2; }
  findExtendable(v, c) {
    const p = this.symbols.length - 1;
    for (;;) {
      const left = p - 1 - this.nodes[v].length;
      if (left >= 0 && this.symbols[left] === c) return v;
      v = this.nodes[v].link;
    }
  }
  append(c) {
    if (typeof c !== "string" || !c.isWellFormed() || [...c].length !== 1) {
      throw new TypeError("one Unicode scalar value required");
    }
    this.symbols.push(c);
    const parent = this.findExtendable(this.last, c);
    let id = this.nodes[parent].next.get(c);
    const created = id === undefined;
    if (created) {
      const length = this.nodes[parent].length + 2;
      let link = 1;
      if (length > 1) {
        const q = this.findExtendable(this.nodes[parent].link, c);
        link = this.nodes[q].next.get(c);
      }
      id = this.nodes.length;
      this.nodes.push({ length, link, next: new Map(), raw: 0,
        end: this.symbols.length - 1 });
      this.nodes[parent].next.set(c, id);
    }
    this.last = id;
    this.nodes[id].raw++;
    return { id, created, distinct: this.distinct };
  }
  appendText(text) {
    if (typeof text !== "string" || !text.isWellFormed()) {
      throw new TypeError("well-formed string required");
    }
    for (const c of text) this.append(c);
    return this;
  }
  snapshot() {
    const counts = this.nodes.map(n => n.raw);
    for (let id = this.nodes.length - 1; id >= 2; id--) {
      counts[this.nodes[id].link] += counts[id];
    }
    return this.nodes.slice(2).map((n, i) => ({
      id: i + 2, length: n.length, firstEnd: n.end,
      occurrences: counts[i + 2]
    }));
  }
  text(id) {
    if (!Number.isInteger(id) || id < 2 || id >= this.nodes.length) {
      throw new RangeError("non-root node id required");
    }
    const n = this.nodes[id];
    return this.symbols.slice(n.end - n.length + 1, n.end + 1).join("");
  }
}
const assert = require("node:assert/strict");
const tree = new Eertree().appendText("aaaa");
const before = tree.nodes.map(n => n.raw);
const first = tree.snapshot();
assert.deepEqual(first, tree.snapshot());
assert.deepEqual(tree.nodes.map(n => n.raw), before);
assert.deepEqual(first.map(n => n.occurrences), [4, 3, 2, 1]);
console.log(JSON.stringify({ raw: before.slice(2),
  totals: first.map(n => [tree.text(n.id), n.occurrences]) }));

输出:

{"raw":[1,1,1,1],"totals":[["a",4],["aa",3],["aaa",2],["aaaa",1]]}

六、快照之后继续追加,旧结果也不能漂移

调用方常常会把上次快照留给前端比较变化,或在后台慢慢序列化。只要快照数组里塞的是内部节点引用,后续更新就可能悄悄改变先前拿到的结果。本文返回新对象,里面只有编号、码点长度、首次结束位置和次数。用户修改这些对象也不应影响树。

这种快照是已处理前缀的频次视图,并不是保存了整棵树的持久化版本。节点编号只在同一个实例内稳定,不能把两个实例中同一个数字当成相同回文。firstEnd 是首次出现时的码点结束下标,追加后保持不变;若需要全部出现位置,必须另外设计输出接口,不能从一个代表位置推断出整张位置清单。

示例六同时检查连续两次快照、快照后追加、旧结果不变和外部修改不回流。这些测试对应真实使用生命周期,比只跑一次最终字符串更能暴露状态污染。线程间共享、持久化恢复、撤销末尾字符都不在当前合同中,不能凭借 append-only 类就推断它们也安全。

独立示例 6,保存为 example-06.cjs 后运行 node example-06.cjs:

"use strict";
class Eertree {
  constructor() {
    this.symbols = [];
    this.nodes = [
      { length: -1, link: 0, next: new Map(), raw: 0, end: -1 },
      { length: 0, link: 0, next: new Map(), raw: 0, end: -1 }
    ];
    this.last = 1;
  }
  get distinct() { return this.nodes.length - 2; }
  findExtendable(v, c) {
    const p = this.symbols.length - 1;
    for (;;) {
      const left = p - 1 - this.nodes[v].length;
      if (left >= 0 && this.symbols[left] === c) return v;
      v = this.nodes[v].link;
    }
  }
  append(c) {
    if (typeof c !== "string" || !c.isWellFormed() || [...c].length !== 1) {
      throw new TypeError("one Unicode scalar value required");
    }
    this.symbols.push(c);
    const parent = this.findExtendable(this.last, c);
    let id = this.nodes[parent].next.get(c);
    const created = id === undefined;
    if (created) {
      const length = this.nodes[parent].length + 2;
      let link = 1;
      if (length > 1) {
        const q = this.findExtendable(this.nodes[parent].link, c);
        link = this.nodes[q].next.get(c);
      }
      id = this.nodes.length;
      this.nodes.push({ length, link, next: new Map(), raw: 0,
        end: this.symbols.length - 1 });
      this.nodes[parent].next.set(c, id);
    }
    this.last = id;
    this.nodes[id].raw++;
    return { id, created, distinct: this.distinct };
  }
  appendText(text) {
    if (typeof text !== "string" || !text.isWellFormed()) {
      throw new TypeError("well-formed string required");
    }
    for (const c of text) this.append(c);
    return this;
  }
  snapshot() {
    const counts = this.nodes.map(n => n.raw);
    for (let id = this.nodes.length - 1; id >= 2; id--) {
      counts[this.nodes[id].link] += counts[id];
    }
    return this.nodes.slice(2).map((n, i) => ({
      id: i + 2, length: n.length, firstEnd: n.end,
      occurrences: counts[i + 2]
    }));
  }
  text(id) {
    if (!Number.isInteger(id) || id < 2 || id >= this.nodes.length) {
      throw new RangeError("non-root node id required");
    }
    const n = this.nodes[id];
    return this.symbols.slice(n.end - n.length + 1, n.end + 1).join("");
  }
}
const assert = require("node:assert/strict");
const tree = new Eertree().appendText("aa");
const old = tree.snapshot();
const saved = JSON.stringify(old);
assert.deepEqual(old, tree.snapshot());
const aId = old[0].id;
tree.append("a");
assert.equal(JSON.stringify(old), saved);
assert.equal(tree.snapshot()[0].id, aId);
assert.deepEqual(tree.snapshot().map(n => n.occurrences), [3, 2, 1]);
const detached = tree.snapshot();
detached[0].occurrences = 999;
assert.equal(tree.snapshot()[0].occurrences, 3);
console.log(JSON.stringify({ old: old.map(n => n.occurrences),
  afterAppend: tree.snapshot().map(n => n.occurrences) }));

输出:

{"old":[2,1],"afterAppend":[3,2,1]}

七、把码点区间映射回原始 UTF-16 字符串

节点的 firstEnd 和 length 都以码点计数。需要拿原字符串做 slice 时,应先计算码点边界对应的 UTF-16 偏移。对一个节点,码点半开区间为 firstEnd - length + 1 到 firstEnd + 1,再查边界表。混用两套单位在 ASCII 样本里不会报错,遇到补充平面字符时才会把代理项截断。

边界表以零开头,逐个累加迭代得到的符号长度。一个符号占一或两个 UTF-16 码元,所以表可在追加时同步维护。下面示例只做映射,完全不依赖回文树;这样可以单独确认界面定位逻辑没有掩盖核心计数错误。若上游做过规范化,这张表只对应转换后的文本,不能直接拿来定位转换前的字符串。

独立示例 7,保存为 example-07.cjs 后运行 node example-07.cjs:

"use strict";
const assert = require("node:assert/strict");
const text = "x😀a😀y";
const offsets = [0];
for (const c of text) offsets.push(offsets.at(-1) + c.length);
// Half-open code-point interval [1, 4).
const start = 1, end = 4;
const selected = text.slice(offsets[start], offsets[end]);
assert.equal(selected, "😀a😀");
assert.equal(offsets[end] - offsets[start], 5);
console.log(JSON.stringify({ offsets, selected,
  utf16Interval: [offsets[start], offsets[end]] }));

输出:

{"offsets":[0,1,3,4,6,7],"selected":"😀a😀","utf16Interval":[1,6]}

八、固定种子差分测试要比较每一个前缀

随机测试的价值取决于断言覆盖了什么。只比较最终不同回文个数,可能放过节点重复、次数错配和中途状态污染。本例每追加一个码点,都将快照转换成内容到次数的映射,与独立区间枚举逐项对照,同时检查映射大小等于节点数,防止两个错误节点合并后把问题藏起来。

字母表包含普通字母、汉字、补充平面符号和组合附加符。它们不是为了模拟自然语言,而是为了打破一个字符总等于一个码元的假设。固定种子让失败可以复现,短长度让慢参考仍然可接受。实际排障时还应把失败的原始码点数组、种子和前缀长度存下来,避免终端显示把组合符号的差异藏住。

每次追加前保存上一份快照的序列化结果,追加后确认它没有变化;同一前缀连续快照必须一致。这里的频次按内容对齐,不依赖节点创建顺序与暴力枚举顺序相同。随机用例可以补充证据,但不能代替对边界、后缀链接含义和计数传播方向的推理。

独立示例 8,保存为 example-08.cjs 后运行 node example-08.cjs:

"use strict";
class Eertree {
  constructor() {
    this.symbols = [];
    this.nodes = [
      { length: -1, link: 0, next: new Map(), raw: 0, end: -1 },
      { length: 0, link: 0, next: new Map(), raw: 0, end: -1 }
    ];
    this.last = 1;
  }
  get distinct() { return this.nodes.length - 2; }
  findExtendable(v, c) {
    const p = this.symbols.length - 1;
    for (;;) {
      const left = p - 1 - this.nodes[v].length;
      if (left >= 0 && this.symbols[left] === c) return v;
      v = this.nodes[v].link;
    }
  }
  append(c) {
    if (typeof c !== "string" || !c.isWellFormed() || [...c].length !== 1) {
      throw new TypeError("one Unicode scalar value required");
    }
    this.symbols.push(c);
    const parent = this.findExtendable(this.last, c);
    let id = this.nodes[parent].next.get(c);
    const created = id === undefined;
    if (created) {
      const length = this.nodes[parent].length + 2;
      let link = 1;
      if (length > 1) {
        const q = this.findExtendable(this.nodes[parent].link, c);
        link = this.nodes[q].next.get(c);
      }
      id = this.nodes.length;
      this.nodes.push({ length, link, next: new Map(), raw: 0,
        end: this.symbols.length - 1 });
      this.nodes[parent].next.set(c, id);
    }
    this.last = id;
    this.nodes[id].raw++;
    return { id, created, distinct: this.distinct };
  }
  appendText(text) {
    if (typeof text !== "string" || !text.isWellFormed()) {
      throw new TypeError("well-formed string required");
    }
    for (const c of text) this.append(c);
    return this;
  }
  snapshot() {
    const counts = this.nodes.map(n => n.raw);
    for (let id = this.nodes.length - 1; id >= 2; id--) {
      counts[this.nodes[id].link] += counts[id];
    }
    return this.nodes.slice(2).map((n, i) => ({
      id: i + 2, length: n.length, firstEnd: n.end,
      occurrences: counts[i + 2]
    }));
  }
  text(id) {
    if (!Number.isInteger(id) || id < 2 || id >= this.nodes.length) {
      throw new RangeError("non-root node id required");
    }
    const n = this.nodes[id];
    return this.symbols.slice(n.end - n.length + 1, n.end + 1).join("");
  }
}
const assert = require("node:assert/strict");
function naive(text) {
  const a = [...text], counts = new Map();
  for (let start = 0; start < a.length; start++) {
    for (let end = start + 1; end <= a.length; end++) {
      let ok = true;
      for (let l = start, r = end - 1; l < r; l++, r--) {
        if (a[l] !== a[r]) { ok = false; break; }
      }
      if (ok) {
        const key = a.slice(start, end).join("");
        counts.set(key, (counts.get(key) ?? 0) + 1);
      }
    }
  }
  return counts;
}
let seed = 0x00e37a11;
function random() {
  seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
  return seed;
}
function ordered(m) {
  return [...m].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
}
const alphabet = ["a", "b", "😀", "中", "\u0301"];
let prefixes = 0;
for (let trial = 0; trial < 400; trial++) {
  const tree = new Eertree();
  let text = "";
  assert.deepEqual(tree.snapshot(), []);
  const length = random() % 19;
  for (let i = 0; i < length; i++) {
    const old = tree.snapshot(), saved = JSON.stringify(old);
    const c = alphabet[random() % alphabet.length];
    text += c; tree.append(c);
    const snap = tree.snapshot();
    const actual = new Map(snap.map(n => [tree.text(n.id), n.occurrences]));
    assert.equal(actual.size, snap.length);
    assert.equal(tree.distinct, naive(text).size);
    assert.deepEqual(ordered(actual), ordered(naive(text)));
    assert.deepEqual(snap, tree.snapshot());
    assert.equal(JSON.stringify(old), saved);
    for (const row of snap) assert.ok(tree.nodes[row.id].link < row.id);
    prefixes++;
  }
}
console.log(JSON.stringify({ trials: 400, prefixes, status: "PASS" }));

输出:

{"trials":400,"prefixes":3853,"status":"PASS"}

九、明确分块边界、拒绝路径与性能预算

append 接受恰好一个完整标量值,appendText 接受一段格式正确的字符串,并在改变状态前验证整段。空文本块合法,单字符 append 的空字符串不合法。无效块中的前半段也不应先被写入,因此验证必须放在循环之前。这个原子性承诺仅针对输入校验失败,不包括内存耗尽等运行时故障。

网络字节流和任意 UTF-16 字符串片段并不自动符合该合同。把一个表情符号的两个代理项分别送入 appendText,会被拒绝。正确做法是在上游使用能保存解码状态的流式解码器,或先拼接残留代理项,再向本接口提交完整码点。这里没有偷偷缓存半个符号,也不提供数据丢弃或替换策略。

最后的回归例覆盖按完整码点分块与整串输入等价、空块不改变结果、七种非法输入不污染状态以及空树快照。测试中的组合附加符仍然按码点参与对称比较。它能组成码点回文,并不意味着终端显示出的字形序列也呈镜像对称。

独立示例 9,保存为 example-09.cjs 后运行 node example-09.cjs:

"use strict";
class Eertree {
  constructor() {
    this.symbols = [];
    this.nodes = [
      { length: -1, link: 0, next: new Map(), raw: 0, end: -1 },
      { length: 0, link: 0, next: new Map(), raw: 0, end: -1 }
    ];
    this.last = 1;
  }
  get distinct() { return this.nodes.length - 2; }
  findExtendable(v, c) {
    const p = this.symbols.length - 1;
    for (;;) {
      const left = p - 1 - this.nodes[v].length;
      if (left >= 0 && this.symbols[left] === c) return v;
      v = this.nodes[v].link;
    }
  }
  append(c) {
    if (typeof c !== "string" || !c.isWellFormed() || [...c].length !== 1) {
      throw new TypeError("one Unicode scalar value required");
    }
    this.symbols.push(c);
    const parent = this.findExtendable(this.last, c);
    let id = this.nodes[parent].next.get(c);
    const created = id === undefined;
    if (created) {
      const length = this.nodes[parent].length + 2;
      let link = 1;
      if (length > 1) {
        const q = this.findExtendable(this.nodes[parent].link, c);
        link = this.nodes[q].next.get(c);
      }
      id = this.nodes.length;
      this.nodes.push({ length, link, next: new Map(), raw: 0,
        end: this.symbols.length - 1 });
      this.nodes[parent].next.set(c, id);
    }
    this.last = id;
    this.nodes[id].raw++;
    return { id, created, distinct: this.distinct };
  }
  appendText(text) {
    if (typeof text !== "string" || !text.isWellFormed()) {
      throw new TypeError("well-formed string required");
    }
    for (const c of text) this.append(c);
    return this;
  }
  snapshot() {
    const counts = this.nodes.map(n => n.raw);
    for (let id = this.nodes.length - 1; id >= 2; id--) {
      counts[this.nodes[id].link] += counts[id];
    }
    return this.nodes.slice(2).map((n, i) => ({
      id: i + 2, length: n.length, firstEnd: n.end,
      occurrences: counts[i + 2]
    }));
  }
  text(id) {
    if (!Number.isInteger(id) || id < 2 || id >= this.nodes.length) {
      throw new RangeError("non-root node id required");
    }
    const n = this.nodes[id];
    return this.symbols.slice(n.end - n.length + 1, n.end + 1).join("");
  }
}
const assert = require("node:assert/strict");
const whole = new Eertree().appendText("😀aba😀");
const chunks = new Eertree();
for (const chunk of ["😀a", "", "b", "a😀"]) chunks.appendText(chunk);
assert.deepEqual(chunks.snapshot(), whole.snapshot());
const before = JSON.stringify(chunks.snapshot());
const size = chunks.symbols.length;
for (const bad of ["", "ab", "\uD83D", "\uDE00", 7, null]) {
  assert.throws(() => chunks.append(bad), TypeError);
}
assert.throws(() => chunks.appendText("ok\uD83D"), TypeError);
assert.equal(chunks.symbols.length, size);
assert.equal(JSON.stringify(chunks.snapshot()), before);
assert.equal(new Eertree().appendText("e\u0301e").distinct, 3);
assert.deepEqual(new Eertree().snapshot(), []);
console.log(JSON.stringify({ chunkEquivalent: true,
  rejectedInputs: 7, unchanged: true, empty: [] }));

输出:

{"chunkEquivalent":true,"rejectedInputs":7,"unchanged":true,"empty":[]}

审查结论:结构、查询与输出成本分别计算

令 n 为已追加码点数,d 为不同非空回文数。节点和转移数量为线性规模,本文还保留完整码点数组,因此内部存储为 O(n)。核心构建的后缀跳转总量是线性的;边字典的成本需要单独计入。平衡树字典可给出 O(n log σ) 构建界限,本文使用 Map,只有在约定其平均操作近似常数的实现模型下才讨论近似线性构建。ECMAScript 对 Map 的要求是平均访问时间次线性,并未保证所有引擎、所有输入下的常数时间。

单次追加仍可能沿很长的后缀链后退,不能把总量摊还的结论当成每次请求都有固定延迟。当前 snapshot 的计数复制、传播和对象生成均为 O(d),另需 O(d) 临时空间。如果每追加一个符号就导出全部节点,累计成本可以达到二次方。在线维护不同回文数量很轻,持续导出全部频次是另一项工作,服务端应根据真正的读取需求控制快照节奏。

text(id) 的成本与该回文长度成正比。给所有节点都重建全文,输出总长度在 aaaa 这样的输入上可以达到二次方。本文的快照故意只携带元数据,完整文本仅在断言和小样本展示时生成。不要把算法内部的线性空间结论搬到包含所有回文全文的 JSON 响应上,也不要在没有配额的情况下接收无限增长的流。

次数存为 Number,每个节点的出现次数不超过已存码点数;本实现受 JavaScript 数组与实际内存容量约束,远早于单节点计数触及安全整数上限。若将各节点次数相加形成总出现次数,应另外评估累加结果的安全整数范围,必要时使用 BigInt。性能测量还应把构建、快照、文本重建和序列化分开,记录运行时版本与输入分布,避免用短样本的毫秒数推断规模保证。

这次 AI 代码审查最后要保住四条界线:符号单位先确定,节点身份由内容决定,原始命中与派生频次分离,查询结果与内部状态脱离。只要测试把完整生命周期跑通,回文树就能成为一个可解释、可继续追加的索引,而不会在第二次导出时悄悄重复计数。

参考资料与复现实验

本文实现与九组验证程序为独立编写,测试环境为 Node.js v24.19.0。文中输出来自对应代码实际运行;随机测试仅使用固定种子,不依赖第三方包。概念配图为本篇单独生成。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。