Skip to content

Commit f8527d2

Browse files
committed
lcs dp
1 parent 4255529 commit f8527d2

File tree

2 files changed

+106
-1
lines changed

2 files changed

+106
-1
lines changed

chapter11/10-MatrixChainMultiplicationRecursive.html chapter11/08-LongestCommonSubsequenceDP.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@
55
<title></title>
66
</head>
77
<body>
8-
8+
<script src="08-LongestCommonSubsequenceDP.js"></script>
99
</body>
1010
</html>
+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
function lcs(wordX, wordY) {
2+
3+
var m = wordX.length,
4+
n = wordY.length,
5+
l = [],
6+
i, j, a, b;
7+
8+
for (i = 0; i <= m; ++i) {
9+
l[i] = [];
10+
for (j = 0; j <= n; ++j) {
11+
l[i][j] = 0;
12+
}
13+
}
14+
15+
for (i=0; i<=m; i++) {
16+
for (j=0; j<=n; j++) {
17+
if (i == 0 || j == 0){
18+
l[i][j] = 0;
19+
20+
} else if (wordX[i-1] == wordY[j-1]) {
21+
l[i][j] = l[i-1][j-1] + 1;
22+
23+
} else {
24+
a = l[i-1][j];
25+
b = l[i][j-1];
26+
l[i][j] = (a > b) ? a : b; //max(a,b)
27+
}
28+
}
29+
console.log(l[i].join());
30+
}
31+
32+
return l[m][n];
33+
}
34+
35+
//complete algorithm that prints the LCS as well
36+
37+
function lcs2(wordX, wordY) {
38+
39+
var m = wordX.length,
40+
n = wordY.length,
41+
l = [],
42+
solution = [],
43+
i, j, a, b;
44+
45+
for (i = 0; i <= m; ++i) {
46+
l[i] = [];
47+
solution[i] = [];
48+
for (j = 0; j <= n; ++j) {
49+
l[i][j] = 0;
50+
solution[i][j] = '0';
51+
}
52+
}
53+
54+
for (i=0; i<=m; i++) {
55+
for (j=0; j<=n; j++) {
56+
if (i == 0 || j == 0){
57+
l[i][j] = 0;
58+
59+
} else if (wordX[i-1] == wordY[j-1]) {
60+
l[i][j] = l[i-1][j-1] + 1;
61+
solution[i][j] = 'diagonal';
62+
63+
} else {
64+
a = l[i-1][j];
65+
b = l[i][j-1];
66+
l[i][j] = (a > b) ? a : b; //max(a,b)
67+
68+
solution[i][j] = (l[i][j] == l[i - 1][j]) ? 'top' : 'left';
69+
}
70+
}
71+
console.log(l[i].join());
72+
console.log(solution[i].join());
73+
}
74+
75+
printSolution(solution, l, wordX, wordY, m, n);
76+
77+
return l[m][n];
78+
}
79+
80+
function printSolution(solution, l, wordX, wordY, m, n){
81+
82+
var a = m, b = n, i, j,
83+
x = solution[a][b],
84+
answer = '';
85+
86+
while (x !== '0') {
87+
if (solution[a][b] === 'diagonal') {
88+
answer = wordX[a - 1] + answer;
89+
a--;
90+
b--;
91+
} else if (solution[a][b] === 'left') {
92+
b--;
93+
} else if (solution[a][b] === 'top') {
94+
a--;
95+
}
96+
x = solution[a][b];
97+
}
98+
99+
console.log('lcs: '+ answer);
100+
}
101+
102+
var wordX = 'acbaed',
103+
wordY = 'abcadf';
104+
105+
console.log(lcs2(wordX, wordY));

0 commit comments

Comments
 (0)