Categories
Algorithms Javascript

Longest Common Substring in JS

Use the following javascript code to find the longest substring (unconnected) among two strings:

const minDistance = function (text1, text2) {
	const m = text1.length,
		n = text2.length,
		dp = new Array(m + 1).fill().map((v) => new Array(n + 1).fill(0));
	for (let i = 1; i <= m; i++)
		for (let j = 1; j <= n; j++)
			if (text1[i - 1] == text2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
			else dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);

	return m + n - 2 * dp[m][n];
};

Leave a Reply

Your email address will not be published. Required fields are marked *