题解 | #公共子串计算#
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
完整代码如下:
while (line1 = readline()) { line2 = readline(); let max = 0; let temp = 0; //分别遍历line1和line2 for (let i = 0; i < line1.length; i++) { for (let j = 0; j < line2.length; j++) { if (line1[i] == line2[j]) { //利用substring方法和getCommonStr函数得到相同字符串长度,并通过max和temp更新最大长度; temp = getCommonStr(line1.substring(i), line2.substring(j)) if (temp > max) { max = temp; }; } } } //返回最大相同字符串长度; console.log(max); } //这个函数相对比较简单,即寻找两个开头相同的string,共同字符串的长度。 function getCommonStr(str1, str2) { let count = 0; let res = ''; for (let i = 0; i < str1.length; i++) { if (str1[i] == str2[i]) { count += 1; } else { break; } } return count; }