经典题目:求两个字符串相同的最长子字符串
function findlongstr(s1, s2) {
var longstr = "";
var maxLength = 0;
for (var i = 0; i < s1.length; i++) {
for (var j = 0; j < s2.length; j++) {
var substring = "";
var k = i;
var l = j;
while (k < s1.length && l < s2.length && s1[k] === s2[l]) {
substring += s1[k];
k++;
l++;
}
if (substring.length > maxLength) {
maxLength = substring.length;
longstr = substring;
}
}
}
return longstr ;
}
var s1 = "abcdefg";
var s2 = "defghij";
var longestCommonSubstring = findlongstr(s1, s2);
console.log("最长相同子字符串: " + longestCommonSubstring); // 输出:defg
思路:通过双重循环遍历,执行外部for循环语句s1[0]:里面的for循环语句:第一轮s1第一个字符s1[0]与s2第一个字符s2[0]匹配,匹配上了,执行while语句:比较两个字符在当前下标的下个字符是否一致s1[1]===s2[1],如果匹配则继续,否则退出while循环,执行第二轮遍历s1第一个字符s1[0]与s2第二个字符s2[1]匹配,重复上面的操作;当遍历完s2所有字符后,执行外部for循环语句s1[1]:...重复第一轮操作,最后比较,赋值。