Created
January 22, 2011 14:46
-
-
Save littlefolk/791161 to your computer and use it in GitHub Desktop.
Longest Common Substring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// via. http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#Python | |
function LCSubstr_str(S, T) { | |
var m = S.length, n = T.length; | |
var L = [], ml = m + 1, nl = n + 1; | |
for (var i = 0; i < ml; i++) { | |
var l = []; | |
for (var j = 0; j < nl; j++) { | |
l.push(0); | |
}; | |
L.push(l); | |
}; | |
var LCS = ""; | |
var longest = 0; | |
for (var i = 0; i < m; i++) { | |
for (var j = 0; j < m; j++) { | |
if (S.charAt(i) == T.charAt(j)) { | |
var v = L[i][j] + 1; | |
L[i + 1][j + 1] = v; | |
if (v > longest) { | |
longest = v; | |
LCS = ""; | |
}; | |
if (v == longest) { | |
LCS += S.slice(i - v + 1, i + 1); | |
}; | |
}; | |
}; | |
}; | |
return LCS; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment