优化这段代码 function findSameStrings(str1, str2) { let sameStrings = []; let newsameStrings = []; let substrings = []; for (let i = 0; i < str1.length; i++) { for (let j = 0; j < str2.length; j++) { let temp = ""; let k = 0; while (str1[i + k] == str2[j + k]) { temp += str1[i + k]; k++; if (i + k >= str1.length || j + k >= str2.length) break; } if (temp.length > 0) { sameStrings.push(temp); } } } sameStrings.sort(function (a, b) { return b.length - a.length; }); for (var i = 0; i < sameStrings.length; i++) { if (sameStrings.indexOf(sameStrings[i]) === i && sameStrings[i].toString().length !== 1) { newsameStrings.push(sameStrings[i]); } } for (let i = 0; i < newsameStrings.length; i++) { if (str2.includes(newsameStrings[i])) { let reg = new RegExp('(' + newsameStrings[i] + ')', 'ig'); str2 = str2.replace(reg, ""); substrings.push(newsameStrings[i]); } } substrings = (substrings.length > 1) ? substrings.join("|") : substrings.join(""); return substrings; }
时间: 2023-05-27 19:07:26 浏览: 78
function findSameStrings(str1, str2) {
let sameStrings = [];
let substrings = [];
for (let i = 0; i < str1.length; i++) {
for (let j = 0; j < str2.length; j++) {
let temp = "";
let k = 0;
while (str1[i + k] == str2[j + k]) {
temp += str1[i + k];
k++;
if (i + k >= str1.length || j + k >= str2.length) break;
}
if (temp.length > 0) {
sameStrings.push(temp);
}
}
}
sameStrings.sort(function (a, b) {
return b.length - a.length;
});
let uniqueStrings = [...new Set(sameStrings)];
for (let i = 0; i < uniqueStrings.length; i++) {
if (sameStrings.indexOf(uniqueStrings[i]) === i) {
substrings.push(uniqueStrings[i]);
}
}
return substrings;
}
阅读全文