题目:编程实现查找两个字符串的最大公共子串
示例:“aocdfe"和"pmcdfa"最大公共子串为"cdf”
注:最大公共子串有不止一个时,只输出第一个最大子串
代码
function findLongestCommonStr(str1, str2) {
let commonStr = '', L1 = str1.length, L2 = str2.length;
//取最短字符串
let shortStr = L1 > L2 ? str2 : str1;
//取最长字符串
let longStr = L2 < L1 ? str1 : str2;
let shortLen = shortStr.length
//从最短字符串开始遍历,遍历长度逐渐减小
for (let i = shortLen; i > 0; i--) {
//不同长度有j种可能
for (let j = 0; j <= shortLen - i; j++) {
//截取最短字符串的子串
commonStr = shortStr.substr(j, i)
//方便查看遍历结果
console.log('commonStr:' + commonStr + ',j:' + j + ',i:' + i);
//查找子串在最长字符串中的位置
if (longStr.indexOf(commonStr) !== -1) return commonStr
}
}
//没有则返回空字符串
return ''
}
let a = findLongestCommonStr('hdfabcdedd', 'aaabcddd')
console.log(a);