Answer:
Explanation:
The following function is written in Java. It takes two strings as parameters and calculates the longest substring between both of them and returns that substring length.
import java.util.*;
class Test
{
public static void main(String[] args)
{
String X = "photograph";
String Y = "tomography";
System.out.println(X + '\n' + Y);
System.out.println("Longest common substring length: " + longestSub(X, Y));
}
static int longestSub(String X, String Y)
{
char[] word1 = X.toCharArray();
char[] word2 = Y.toCharArray();
int length1 = X.length();
int length2 = Y.length();
int substringArray[][] = new int[length1 + 1][length2 + 1];
int longestSubstringLength = 0;
for (int i = 0; i <= length1; i++)
{
for (int j = 0; j <= length2; j++)
{
if (i == 0 || j == 0)
substringArray[i][j] = 0;
else if (word1[i - 1] == word2[j - 1])
{
substringArray[i][j]
= substringArray[i - 1][j - 1] + 1;
longestSubstringLength = Integer.max(longestSubstringLength,
substringArray[i][j]);
}
else
substringArray[i][j] = 0;
}
}
return longestSubstringLength;
}
}