-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1143-longest-common-subsequence.js
More file actions
69 lines (57 loc) · 1.98 KB
/
Copy path1143-longest-common-subsequence.js
File metadata and controls
69 lines (57 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
- Subproblem: lcs(i, j) where i and j are the suffix subsequences for text1 and text2
- Relation: max( lcs(i+1, j), lcs(i, j+1) ) in case letters don't match, else 1 + lcs(i + 1, j + 1)
- Topological order: ascending i and j
- Base case: either of the sufixes are empty
- Original Problem: lcs(0,0)
- Time: linear time text1.length * text2.length
*/
var longestCommonSubsequence = function (text1, text2) {
const result = longestCommonSubsequenceBottomTop(text1, text2);
// const result = longestCommonSubsequenceTopBottom(text1, text2);
return result;
}
var longestCommonSubsequenceBottomTop = function (text1, text2) {
const dp = Array.from({length: text1.length + 1}, () => Array.from({length: text2.length + 2}, () => 0));
for(let i = text1.length - 1; i >= 0; i--) {
for(let j = text2.length - 1; j >= 0; j--) {
if (text1[i] === text2[j]) {
dp[i][j] = 1 + dp[i + 1][j + 1];
} else {
dp[i][j] = Math.max(dp[i][j + 1], dp[i + 1][j]);
}
}
}
return dp[0][0];
}
var longestCommonSubsequenceTopBottom = function (text1, text2) {
const memo = {};
const lcs = (i, j) => {
const key = `${i}-${j}`;
if (memo[key] !== undefined) {
return memo[key];
}
if (i >= text1.length || j >= text2.length) {
return 0;
}
memo[key] = (text1[i] === text2[j])
? 1 + lcs(i + 1, j + 1)
: Math.max(lcs(i + 1, j), lcs(i, j + 1));
return memo[key];
};
return lcs(0, 0);
};
const data = [
{ text1: "hieroglyphology", text2: "michaelangelo", output: 5 },
{ text1: "abcde", text2: "ace", output: 3 },
{ text1: "abc", text2: "abc", output: 3 },
{ text1: "abc", text2: "def", output: 0 },
{ text1: "pmjghexybyrgzczy", text2: "hafcdqbgncrcbihkd", output: 4 },
];
for (let d of data) {
console.log(JSON.stringify(d));
const result = longestCommonSubsequence(d.text1, d.text2);
console.log('result = ', result);
(result === d.output) ? console.log('ok') : console.error('nok');
console.log('----------');
}