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
相关产品推荐
相关产品推荐

