题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void async function () {
// Write your code here
while(line = await readline()){
// 首先得找出 两个字符串中, 最大和最小的分别是哪个?
// 记录 2个 变量,一个是 最长 长度 l, 一个 公共子串res
// 找到后 先从最小的 那个开始遍历, 以 i -> short.length
// 然后再 遍历, 以 j = i -> short.length
// 在 short 里 截取字符串 i --> j+1
// 如果 最长的里面找到了 截取的串, 并且 串的长度 > 最长长度 l, 把最长子串更新为截取的值, 把最长长度更新为 截取串的长度
// 输入结果 res
const line1 = line;
const line2 = await readline();
let short = line1.length < line2.length ? line1 : line2;
let long = line1.length < line2.length ? line2 : line1;
let len = 0;
let res = '';
for (let i = 0; i < short.length; i++){
for (let j = i; j < short.length; j++) {
let str = short.substring(i, j+1);
if (long.includes(str)) {
if (str.length > len) {
res = str;
len = res.length;
}
}
}
}
console.log(res);
}
}()