Skip to content

Commit 57989d5

Browse files
Add docs for longest common subsequence algorithm
1 parent b589f9b commit 57989d5

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/searching/longest-common-subsequence.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,19 @@
33

44
exports.longestCommonSubsequence = (function () {
55

6+
/**
7+
* Find the lengths of longest common sub-sequences
8+
* of two strings and their substrings.
9+
*
10+
* Complexity: O(MN).
11+
*
12+
* @private
13+
* @param {String} first string
14+
* @param {String} second string
15+
* @return {Array} two dimensional array with LCS
16+
* lengths of input strings and their substrings.
17+
*
18+
*/
619
function getLcsLengths(str1, str2) {
720
var result = [];
821
for (var i = -1; i < str1.length; i = i + 1) {
@@ -20,6 +33,19 @@
2033
return result;
2134
}
2235

36+
/**
37+
* Find longest common sub-sequences of two strings.
38+
*
39+
* Complexity: O(M + N).
40+
*
41+
* @private
42+
* @param {String} first string
43+
* @param {String} second string
44+
* @return {Array} two dimensional array with LCS
45+
* lengths of input strings and their substrings
46+
* returned from 'getLcsLengths' function.
47+
*
48+
*/
2349
function getLcs(str1, str2, lcsLengthsMatrix) {
2450
var execute = function (i, j) {
2551
if (!lcsLengthsMatrix[i][j]) {
@@ -35,6 +61,22 @@
3561
return execute(str1.length - 1, str2.length - 1);
3662
}
3763

64+
/**
65+
* Algorithm from dynamic programming. It finds the longest
66+
* common sub-sequence of two strings. For example for strings 'abcd'
67+
* and 'axxcda' the longest common sub-sequence is 'acd'.
68+
*
69+
* @example
70+
* var subsequence = require('path-to-algorithms/src/searching/'+
71+
* 'longest-common-subsequence').longestCommonSubsequence;
72+
* console.log(subsequence('abcd', 'axxcda'); // 'acd'
73+
*
74+
* @public
75+
* @module searching/longest-common-subsequence
76+
* @param {String} first input string.
77+
* @param {String} second input string.
78+
* @return {Array} Longest common subsequence.
79+
*/
3880
return function (str1, str2) {
3981
var lcsLengthsMatrix = getLcsLengths(str1, str2);
4082
return getLcs(str1, str2, lcsLengthsMatrix);

0 commit comments

Comments
 (0)