Skip to content

Instantly share code, notes, and snippets.

@littlefolk
Created January 22, 2011 14:46
Show Gist options
  • Save littlefolk/791161 to your computer and use it in GitHub Desktop.
Save littlefolk/791161 to your computer and use it in GitHub Desktop.
Longest Common Substring
// 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