Reputation: 15
I saw this script in another thread on stack overflow and tried to play around with it. Now to the problem, the script works fine in all browsers except internet explorer (I'm using version 7), here it only returns the first string (or the first row of that string if it is a larger one) but in all other browsers it returns what I want, in other words the longest common substring. And I was just wondering if there is some obvious error in this code below that some of you bright fellows out there can point out that Internet explorer doesn't like, and if so how to improve it? Thanks in advance =)
function longestCommonSubstring(string1, string2){
// init max value
var longestCommonSubstring = 0;
var theCommonString = '';
// 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];
theCommonString = string1.substr(i + 1 - longestCommonSubstring, longestCommonSubstring);
}
} else {
table[i+1][j+1] = 0;
}
}
}
return theCommonString;
}
EDIT___________________________________________________________
This is how my code now looks like after the improvments that has been suggested, but it still doesn't work in internet explorer it just (in my case) returns the first row of the file.
function longestCommonSubstring(string1, string2){
// init max value
var longestCommonSubstring = 0;
var theCommonString = '';
var a;
var b;
// init 2D array with 0
var table = [string1.length];
for(a = 0; a <= string1.length; a++){
table[a] = [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];
theCommonString = string1.substr(i + 1 - longestCommonSubstring, longestCommonSubstring);
}
} else {
table[i+1][j+1] = 0;
}
}
}
return theCommonString;
}
Upvotes: 0
Views: 139
Reputation: 38442
IE7 doesn't let you access strings as arrays as you're doing; you'll need to use the substring property instead:
if(string1.substring(i, i + 1)==string2.substring(j, j + 1)){
in case you're wondering, I figured it out by placing alert statements here and there: after the string comparison was successful, Firefox showed "a=a" but IE7 showed "undefined=undefined" :^\
Upvotes: 2