Skip to content

Instantly share code, notes, and snippets.

@crimx
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crimx/a81c149ac98a5de2b14e to your computer and use it in GitHub Desktop.
Save crimx/a81c149ac98a5de2b14e to your computer and use it in GitHub Desktop.
Bottom-up DP for longest common substring (not subsequence). http://jsperf.com/crimx-lcstr/2
/**
* Bottom-up DP for longest common substring (not subsequence).
* Time: O(m*n)
* Space: O(min(m,n))
* @author Jesse Wong (@straybugs)
*/
function lcstr(sstr, lstr) {
'use strict';
if (typeof(sstr) !== 'string' || typeof(lstr) !== 'string') {
return '';
}
// sstr should be shorter
if (sstr.length > lstr.length) {
sstr = [lstr, lstr = sstr][0];
}
var slen = sstr.length
, llen = lstr.length
, memo = []
, maxValue = 0
, maxIndex = 0
, i, j, k
;
// note the "<=", leave memo[0] to lstr.
for (i = 0; i <= slen; i += 1) {
memo[i] = 0;
}
for (i = 0; i < llen; i += 1) {
// must traverse backward
for (j = slen-1; j >= 0; j -= 1) {
// remember the memo got 1 offset
k = j+1;
if (lstr.charAt(i) === sstr.charAt(j)) {
memo[k] = memo[j] + 1;
if (maxValue < memo[k]) {
maxValue = memo[k];
maxIndex = k;
}
} else {
memo[k] = 0;
}
}
}
return sstr.slice(maxIndex-maxValue, maxIndex);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment