提问人:Martin Janíček 提问时间:10/12/2023 最后编辑:Martin Janíček 更新时间:10/13/2023 访问量:99
JavaScript 中两个字符串的最长公共后缀 [已关闭]
Longest common suffix of two strings in JavaScript [closed]
问:
我正在寻找在 JavaScript 中找到两个字符串的最长公共后缀的最简单方法。
我发现了一个关于最长通用前缀的问题,但是
- (a) 对于一个字符串数组而不仅仅是两个字符串,这是一个普遍的问题,这为我的需要增加了代码不必要的复杂性
- (b) 它是前缀,而不是后缀。我可以在运行前缀算法之前和之后反转输入字符串以获得相同的结果,但这在将来并不容易阅读,所以我宁愿寻找最短、最不言自明的代码片段。
答:
1赞
Martin Janíček
10/12/2023
#1
以相反的顺序循环访问两个字符串的字符,直到找到差异。
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;
};
0赞
Gabe Gates
10/12/2023
#2
为了好玩,我提供了一个替代解决方案,它首先将字符串转换为数组,然后找到公共后缀。
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));
1赞
Stephane Moreau
10/13/2023
#3
您可以使用以下命令:
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: ""
评论