题解 | #公共子串计算#
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let str1: string, str2: string;
rl.on("line", function (line) {
if (str1 === undefined) {
str1 = line;
} else {
let res = 0;
str2 = line;
for(let i=0;i<str1.length;i++){ // 遍历第一个字符串
let j=i
while(j>=0){ // 每次都需要查找当前字符和前面若干字符组成的子串,子串是第二个字符串的公共子串则记录长度,不是则继续遍历第一个字符串的下一个字符
const subStr=str1.slice(j,i+1)
if(str2.includes(subStr)){
res=Math.max(res,i-j+1)
j--
}else{
break
}
}
}
console.log(res);
}
});
暴力求解,每次遍历都去判断得到的子串是不是公共子串

查看1道真题和解析
