Skip to content

Instantly share code, notes, and snippets.

@me-shaon
Created November 11, 2023 13:34
Show Gist options
  • Save me-shaon/957a19018810e61d3e02e9f03edd5780 to your computer and use it in GitHub Desktop.
Save me-shaon/957a19018810e61d3e02e9f03edd5780 to your computer and use it in GitHub Desktop.
Longest Common Subsequence (Javascript
module.exports = {
//param A : string
//param B : string
//return an integer
solve : function(A, B){
let rows = A.length, cols = B.length;
let lcs = Array.from({ length: rows + 1 }, () => Array.from({ length: cols + 1 }).fill(0));
for (let i=1;i<=rows;i++) {
for (let j=1;j<=cols;j++) {
if (A[i-1] === B[j-1]) {
lcs[i][j] = lcs[i-1][j-1] + 1;
} else {
lcs[i][j] = Math.max(lcs[i-1][j], lcs[i][j-1]);
}
}
}
return lcs[rows][cols];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment