题目描述
给定两个字符串str1和str2,输出两个字符串的最长公共子串,如果最长公共子串为空,输出-1。
题目解析
- 如果str1和str2不存在则返回-1
- 如果str1的长度大于str2的长度则互换
- 创建储存最大长度和字符串的变量
- 循环短的字符串,如果能在长的字符串当中找到短的字符串当前项到前面最大长度这部分的字符串,则为储存字符串的变量赋值,且储存最大长度的变量加一
- 最后返回储存字符串的变量或者-1
算法
function LCS(str1, str2) {
if (!str1 || !str2) return -1;
if (str1.length > str2.length) {
[str1, str2] = [str2, str1];
}
let max = 0,
res = "";
for (let i = 0; i < str1.length; i++) {
if (str2.indexOf(str1.slice(i - max, i + 1)) !== -1) {
res = str1.slice(i - max, i + 1);
max += 1;
}
}
return res || -1;
}