|
3 | 3 |
|
4 | 4 | exports.longestCommonSubsequence = (function () { |
5 | 5 |
|
| 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 | + */ |
6 | 19 | function getLcsLengths(str1, str2) { |
7 | 20 | var result = []; |
8 | 21 | for (var i = -1; i < str1.length; i = i + 1) { |
|
20 | 33 | return result; |
21 | 34 | } |
22 | 35 |
|
| 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 | + */ |
23 | 49 | function getLcs(str1, str2, lcsLengthsMatrix) { |
24 | 50 | var execute = function (i, j) { |
25 | 51 | if (!lcsLengthsMatrix[i][j]) { |
|
35 | 61 | return execute(str1.length - 1, str2.length - 1); |
36 | 62 | } |
37 | 63 |
|
| 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 | + */ |
38 | 80 | return function (str1, str2) { |
39 | 81 | var lcsLengthsMatrix = getLcsLengths(str1, str2); |
40 | 82 | return getLcs(str1, str2, lcsLengthsMatrix); |
|
0 commit comments