Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b589f9b

Browse files
Implement longest common subsequence algorithm
1 parent f839af2 commit b589f9b

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
(function (exports) {
2+
'use strict';
3+
4+
exports.longestCommonSubsequence = (function () {
5+
6+
function getLcsLengths(str1, str2) {
7+
var result = [];
8+
for (var i = -1; i < str1.length; i = i + 1) {
9+
result[i] = [];
10+
for (var j = -1; j < str2.length; j = j + 1) {
11+
if (i === -1 || j === -1) {
12+
result[i][j] = 0;
13+
} else if (str1[i] === str2[j]) {
14+
result[i][j] = result[i - 1][j - 1] + 1;
15+
} else {
16+
result[i][j] = Math.max(result[i - 1][j], result[i][j - 1]);
17+
}
18+
}
19+
}
20+
return result;
21+
}
22+
23+
function getLcs(str1, str2, lcsLengthsMatrix) {
24+
var execute = function (i, j) {
25+
if (!lcsLengthsMatrix[i][j]) {
26+
return '';
27+
} else if (str1[i] === str2[j]) {
28+
return execute(i - 1, j - 1) + str1[i];
29+
} else if (lcsLengthsMatrix[i][j - 1] > lcsLengthsMatrix[i - 1][j]) {
30+
return execute(i, j - 1);
31+
} else {
32+
return execute(i - 1, j);
33+
}
34+
};
35+
return execute(str1.length - 1, str2.length - 1);
36+
}
37+
38+
return function (str1, str2) {
39+
var lcsLengthsMatrix = getLcsLengths(str1, str2);
40+
return getLcs(str1, str2, lcsLengthsMatrix);
41+
};
42+
})();
43+
44+
})(typeof window === 'undefined' ? module.exports : window);

0 commit comments

Comments
 (0)