题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
let arr = []
let n = 2;
while(line = readline()) {
arr.push(line);
}
for (let s= 0; s< arr.length/n; s++) {
let items = arr.slice(n*s, n*(s+1));
let [str1 , str2] = items;
let short = str1.length > str2.length ? str2 : str1;
let long = short == str2 ? str1 : str2;
let maxLen = 0;
let maxStr;
for (let i=0; i< short.length; i++) {
for (let j=0; j< long.length; j++) {
let a = i;
let b = j;
let length = 0;
let end;
while(a < short.length && b < long.length && short[a] == long[b]) {
a++;
b++;
length++;
end = a;
}
if (length > maxLen) {
maxLen = length;
maxStr = short.substring(i, end);
}
}
}
print(maxStr)
}