Skip to content

Commit e8f040d

Browse files
author
baochau.dinh
committed
js-concepts: dynamic programming - lcs
1 parent f074c7a commit e8f040d

File tree

4 files changed

+88
-0
lines changed

4 files changed

+88
-0
lines changed

Dynamic Programming/LCS_iterative.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* Checking whether a string (B) is a sequence of another string (A)
3+
*/
4+
5+
function main(A = '', B = '') {
6+
if (A.length === 0 || B.length === 0) return '';
7+
8+
let result = 0;
9+
let i = 0, j = 0;
10+
while (i < A.length && j < B.length) {
11+
if (A[i] === B[j]) {
12+
result++
13+
i++;
14+
j++;
15+
} else {
16+
i++;
17+
}
18+
}
19+
return result === B.length;
20+
} // O(A.length + B.length)
21+
22+
console.log(main('abcdgh', 'acdga'));
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Longest common subsequence - LCS
3+
*
4+
* memoization solution
5+
*/
6+
7+
function main(a = '', b = '') {
8+
const lcs = (m, n) => {
9+
if (m < 0 || n < 0) return 0;
10+
11+
if (a[m] === b[n]) return lcs(m - 1, n - 1) + 1;
12+
else return Math.max(lcs(m, n - 1), lcs(m - 1, n));
13+
}
14+
15+
return lcs(a.length - 1, b.length - 1);
16+
}
17+
18+
function mainV2(a = '', b = '') {
19+
let lcs = new Array(a.length + 1).fill(0).map(x => new Array(b.length + 1).fill(0));
20+
21+
for (let i = 1; i <= a.length; i++) {
22+
for (let j = 1; j <= b.length; j++) {
23+
if (a[i - 1] === b[j - 1]) {
24+
lcs[i][j] = lcs[i - 1][j - 1] + 1;
25+
}
26+
else {
27+
lcs[i][j] = Math.max(lcs[i][j - 1], lcs[i - 1][j]);
28+
}
29+
}
30+
}
31+
32+
return lcs[a.length][b.length];
33+
}
34+
35+
console.log(mainV2('aab', 'ba'));

Dynamic Programming/LCS_recursive.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* Longest common subsequence - LCS
3+
*
4+
* recursive solution
5+
*/
6+
7+
function main(a = '', b = '') {
8+
const lcs = (m, n) => {
9+
if (m < 0 || n < 0) return 0;
10+
11+
if (a[m] === b[n]) return lcs(m - 1, n - 1) + 1;
12+
else return Math.max(lcs(m, n - 1), lcs(m - 1, n));
13+
}
14+
15+
return lcs(a.length - 1, b.length - 1);
16+
}
17+
18+
console.log(main('aabb', 'ab'));
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/**
2+
* Given a string A, remove some characters to receive string B (sequences)
3+
* Write a function to find the longest palindrome among B
4+
*/
5+
6+
function main(a = '') {
7+
if (a.length === 0) return 0;
8+
9+
let i = 0, j = a.length - 1;
10+
while (i <= j) {
11+
12+
}
13+
}

0 commit comments

Comments
 (0)