题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); let row = 0 let [sMin, sMax] = ['', ''] // 保存出现的子串及其长度,二维数组形式 const arr = [] let maxLen = 0 rl.on('line', function (line) { row++ if(row === 1){ sMin = line }else { sMax = line // 確保sMin 是较短的字符串, sMax是较长的 if(sMin.length > sMax.length){ [sMin, sMax] = [sMax, sMin] } // 遍历较短字符串,找所有公共子串 // 记录子串中长度越来越大的, 子串长度不比已经出现过的子串长,就不记录 for(let i = 0; i < sMin.length; i++){ for(let j = i; j < sMin.length; j++){ const key = sMin.slice(i, j+1) // 确保是公共子串,并且长度大于maxLen if(sMax.includes(key) && key.length > maxLen ){ maxLen = key.length arr.push([key, key.length]) } } } console.log(arr.find((item)=>item[1] === maxLen)[0]) } });