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

JavaScript中两个字符串的最长公共后缀求解方法

JavaScript 求两个字符串的最长公共后缀(最简可读版)

方法一:从末尾逐字符匹配(高效直观)

直接从两个字符串的末尾同步向前遍历,收集匹配的字符,直到出现不匹配或其中一个字符串遍历完成:

function longestCommonSuffix(a, b) {
  let i = a.length - 1, j = b.length - 1;
  let suffix = '';
  while (i >= 0 && j >= 0 && a[i] === b[j]) {
    suffix = a[i] + suffix;
    i--;
    j--;
  }
  return suffix;
}

示例用法:

console.log(longestCommonSuffix('hello world', 'goodbye world')); // ' world'
console.log(longestCommonSuffix('abcde', 'cde')); // 'cde'
console.log(longestCommonSuffix('test', 'none')); // ''

方法二:利用原生 endsWith API(极简语义化)

借助原生字符串方法endsWith,从较短字符串的最长可能后缀开始检查,找到第一个同时满足两个字符串结尾匹配的结果:

function longestCommonSuffix(a, b) {
  const shorter = a.length <= b.length ? a : b;
  for (let i = shorter.length; i >= 0; i--) {
    const candidate = shorter.slice(i);
    if (a.endsWith(candidate) && b.endsWith(candidate)) {
      return candidate;
    }
  }
  return '';
}

优势:代码更简洁,endsWith的语义化让逻辑一目了然,几乎不需要额外注释就能理解。


内容的提问来源于stack exchange,提问作者Martin Janíček

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:52:37