请快速浏览一下我在网上找到的这个函数。如何修改此函数返回字符串而不是int
function longestCommonSubstring(string1, string2){
// init max value
var longestCommonSubstring = 0;
// init 2D array with 0
var table = Array(string1.length);
for(a = 0; a <= string1.length; a++){
table[a] = Array(string2.length);
for(b = 0; b <= string2.length; b++){
table[a][b] = 0;
}
}
// fill table
for(var i = 0; i < string1.length; i++){
for(var j = 0; j < string2.length; j++){
if(string1[i]==string2[j]){
if(table[i][j] == 0){
table[i+1][j+1] = 1;
} else {
table[i+1][j+1] = table[i][j] + 1;
}
if(table[i+1][j+1] > longestCommonSubstring){
longestCommonSubstring = table[i+1][j+1];
}
} else {
table[i+1][j+1] = 0;
}
}
}
return longestCommonSubstring;
}
它以int形式返回最长公共子串的长度。现在我的问题是,是否有可能修改此函数,以便它返回实际的字符串,而不是仅返回子字符串的长度,我在编程方面颇为新颖,并且认为只是修改这个secetion会帮助if(string1[i]==string2[j]){ push(string1[i]}
,但它并不是那么容易,因为我不希望在这两个字符串中的每个字符都被添加到该数组中,只有那些完全相同的字符才会被添加。 在此先感谢=)