@technobuddha/library
Version:
A large library of useful functions
49 lines (48 loc) • 2.01 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.longestCommonSubstring = void 0;
var create2DArray_1 = __importDefault(require("../create2DArray"));
/**
* Implementation of Longest Common Substring problem.
* https://en.wikipedia.org/wiki/Longest_common_substring_problem
*
* Returns the longest possible substring that is substring of both of given strings.
*
* @param array1 First string.
* @param array2 Second string.
* @returns A string that is common to both strings such that there is no
* common substring with size greater than the length of the string.
*/
function longestCommonSubstring(string1, string2, _a) {
var _b = _a === void 0 ? {} : _a, _c = _b.caseInsensitive, caseInsensitive = _c === void 0 ? false : _c;
var ci1 = caseInsensitive ? string1.toLowerCase() : string1;
var ci2 = caseInsensitive ? string2.toLowerCase() : string2;
var comparsions = create2DArray_1.default(ci1.length + 1, ci2.length + 1, 0);
var maxSubStrLength = 0;
var lastMaxSubStrIndex = -1;
for (var i = 0; i < ci1.length; ++i) {
var c1 = ci1.charAt(i);
for (var j = 0; j < ci2.length; ++j) {
var c2 = ci2.charAt(j);
if (c1 === c2) {
if (i > 0 && j > 0)
comparsions[i][j] = comparsions[i - 1][j - 1] + 1;
else
comparsions[i][j] = 1;
}
else {
comparsions[i][j] = 0;
}
if (comparsions[i][j] > maxSubStrLength) {
maxSubStrLength = comparsions[i][j];
lastMaxSubStrIndex = i;
}
}
}
return string1.slice(lastMaxSubStrIndex - maxSubStrLength + 1, lastMaxSubStrIndex + 1);
}
exports.longestCommonSubstring = longestCommonSubstring;
exports.default = longestCommonSubstring;