You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript如何在单词数组中检测唯一语句并返回匹配词项

TypeScript 单词数组唯一目标语句匹配实现

你原先用字符串拼接+indexOf的方案存在天然缺陷:字符位置和原单词数组的下标没有直接映射关系,不同单词长度不一致,拿到字符索引后无法准确定位到对应的原单词对象,还可能出现跨单词误匹配的问题(比如相邻单词的首尾字符刚好拼成搜索词的情况)。

直接在原单词数组上用滑动窗口做匹配是更可靠的实现方式,核心逻辑如下:

  • 先将输入的搜索语句按空白符拆分为独立的搜索词序列,统一转小写实现大小写不敏感匹配,自动过滤空内容
  • 以搜索词序列的长度为窗口大小,遍历原单词数组逐窗口比对内容是否完全一致
  • 收集所有匹配成功的窗口对应的原单词对象集合
  • 最终匹配结果必须恰好为1组,否则抛出Non unique anchor错误;匹配唯一时直接返回对应单词对象数组

完整实现代码:

interface Word {
  id: number;
  content: string;
}

const words: Word[] = [
  { id: 1, content: "date" },
  { id: 2, content: "of" },
  { id: 3, content: "my" },
  { id: 4, content: "birthday" },
  { id: 5, content: "date" },
  { id: 6, content: "of" },
  { id: 7, content: "his" },
  { id: 8, content: "birthday" },
];

function findText(searchStr: string, wordList: Word[]): Word[] {
  // 处理搜索词:兼容多空格、首尾空格场景,统一转小写
  const searchWords = searchStr.trim().toLowerCase().split(/\s+/).filter(Boolean);
  const searchLen = searchWords.length;
  const totalWords = wordList.length;

  if (searchLen === 0) return [];
  if (searchLen > totalWords) throw new Error("Non unique anchor");

  const matchedGroups: Word[][] = [];

  // 滑动窗口遍历匹配
  for (let windowStart = 0; windowStart <= totalWords - searchLen; windowStart++) {
    const isMatch = searchWords.every((word, offset) => {
      return wordList[windowStart + offset].content.toLowerCase() === word;
    });
    if (isMatch) {
      matchedGroups.push(wordList.slice(windowStart, windowStart + searchLen));
    }
  }

  if (matchedGroups.length !== 1) {
    throw new Error("Non unique anchor");
  }

  return matchedGroups[0];
}

测试用例验证

  • 执行findText("date", words):共匹配到2组结果(id1/date、id5/date),抛出Non unique anchor错误
  • 执行findText("date of", words):共匹配到2组结果(id1-2/date of、id5-6/date of),抛出Non unique anchor错误
  • 执行findText("date of his", words):仅匹配到1组结果,返回值如下,完全符合需求:
[
  { id: 5, content: "date" },
  { id: 6, content: "of" },
  { id: 7, content: "his" },
]

这个方案相比字符串拼接的实现更稳定,不会出现跨单词误匹配问题,也不需要额外做索引转换,直接就能拿到完整的原单词对象属性。

内容的提问来源于stack exchange,提问作者Dylan Grum's

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 04:18:21