题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
function getMaxSubStr(str1, str2) { // 较短串转换为数组 const strShortArr = str1.length < str2.length ? str1.split('') : str2.split(''); // 较长串作为基准 const strLong = str1.length < str2.length ? str2 : str1; let subStr = ''; let temp = ''; let index = 0; while (strShortArr.length) { // 提前到最后一个字符 if (!strShortArr[index]) { return temp.length > subStr.length ? temp : subStr; } temp += strShortArr[index] ? strShortArr[index] : ''; if (strLong.indexOf(temp) === -1) { if (temp.length - 1 > subStr.length) { subStr = temp.substring(0, temp.length - 1); } temp = ''; strShortArr.shift(); index = 0; } else { index++; } } return subStr; } const line1 = readline(); const line2 = readline(); print(getMaxSubStr(line1, line2));