|
| 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