Created
November 22, 2014 23:59
-
-
Save greduan/fe88e02be6db7a3c4b7e to your computer and use it in GitHub Desktop.
LCS algorithm in JS. Prettified version of what can be found here: https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_subsequence#JavaScript
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
// prettified version of what can be found here: | |
// https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_subsequence#JavaScript | |
function LCS(a, b) { | |
var m = a.length, | |
n = b.length, | |
C = [], | |
i, | |
j; | |
for (i = 0; i <= m; i++) C.push([0]); | |
for (j = 0; j < n; j++) C[0].push(0); | |
for (i = 0; i < m; i++) { | |
for (j = 0; j < n; j++) { | |
C[i+1][j+1] = a[i] === b[j] | |
? C[i][j]+1 | |
: Math.max(C[i+1][j], C[i][j+1]); | |
} | |
} | |
return (function bt(i, j) { | |
if (i * j === 0) { | |
return ''; | |
} | |
if (a[i-1] === b[j-1]) { | |
return bt(i-1, j-1) + a[i-1]; | |
} | |
return (C[i][j-1] > C[i-1][j]) | |
? bt(i, j-1) | |
: bt(i-1, j); | |
}(m, n)); | |
} | |
console.log(LCS('dis a test bra manyo', 'this is a test, brother yo')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment