JavaScript中两个字符串的最长公共后缀[已关闭]

1szpjjfi  于 12个月前  发布在  Java
关注(0)|答案(3)|浏览(101)

已关闭,此问题为opinion-based。它目前不接受回答。
**想改善这个问题吗?**更新问题,以便editing this post可以用事实和引用来回答。

19小时前关闭
Improve this question
我正在寻找最简单的方法来找到最长的共同后缀的两个字符串在JavaScript。
我找到了a question about longest common prefix但是

  • (a)这是一个字符串数组的一般问题,而不是仅仅两个字符串,这为我的需要增加了不必要的代码复杂性
  • (B)是前缀,不是后缀。我可以在运行前缀算法之前和之后反转输入字符串,以获得相同的结果,但这并不容易在未来阅读,所以我宁愿寻找最短,最不言自明的代码片段。
kmbjn2e3

kmbjn2e31#

为了好玩,我提供了一个替代解决方案,首先将字符串转换为数组,然后找到公共后缀。

let a = '123567';
let b = '124567';

function commonSuffix(a, b) {
  let arrayA = [...a].reverse(), arrayB = [...b].reverse();
                
  let match = [];
  arrayA.every((item, i) => arrayB[i] === item && match.unshift(item));
  return match.join('');
}

console.log(commonSuffix(a, b));
vmpqdwk3

vmpqdwk32#

你可以使用这个:

function longestCommonSuffix(str1, str2) {
    let i = 0;
    while (i < str1.length && i < str2.length && str1[str1.length - 1 - i] === str2[str2.length - 1 - i]) {
        i++;
    }
    return str1.slice(str1.length - i);
}

// Example usage:
console.log(longestCommonSuffix("programming", "coding")); // Outputs: "ing"
console.log(longestCommonSuffix("hello", "world"));       // Outputs: ""
yyhrrdl8

yyhrrdl83#

以相反的顺序迭代两个字符串的字符,直到找到差异。

const commonSuffix = (str1: string, str2: string) => {
    for (let i1 = str1.length - 1, i2 = str2.length - 1; i1 >= 0 && i2 >= 0; i1--, i2--) {
        if (str1[i1] !== str2[i2]) {
            return str1.substr(i1 + 1);
        }
    }
    return str1.length < str2.length ? str1 : str2;
};

相关问题