Comstr
Comstr
#include <iostream>
#include <cstring>
using namespace std;
void longestCommonSubstring(char *X, char *Y)
{
int m = strlen(X);
int n = strlen(Y);
int LCSuff[m + 1][n + 1];
int result = 0;
int endIndex = 0;
cout << "Initialization:" << endl;
cout << " ";
for (int j = 0; j <= n; j++)
{
cout << Y[j] << " ";
}
cout << endl;
for (int i = 0; i <= m; i++)
{
if (i == 0)
{
cout << " ";
}
else
{
cout << X[i - 1] << " ";
}
for (int j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
{
LCSuff[i][j] = 0;
}
else if (X[i - 1] == Y[j - 1])
{
LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1;
if (LCSuff[i][j] > result)
{
result = LCSuff[i][j];
endIndex = i - 1;
}
}
else
{
LCSuff[i][j] = 0;
}
cout << LCSuff[i][j] << " ";
}
cout << endl;
}
cout << "\nFinal LCSuff Table:" << endl;
cout << " ";
for (int j = 0; j <= n; j++)
{
cout << Y[j] << " ";
}
cout << endl;
for (int i = 0; i <= m; i++)
{
if (i == 0)
{
cout << " ";
}
else
{
cout << X[i - 1] << " ";
}
for (int j = 0; j <= n; j++)
{
cout << LCSuff[i][j] << " ";
}
cout << endl;
}
if (result == 0)
{
cout << "\nNo common substring found." << endl;
}
else
{
cout << "\nLongest common substring: ";
for (int i = endIndex - result + 1; i <= endIndex; i++)
{
cout << X[i];
}
cout << endl;
}
}
int main()
{
char str1[100], str2[100];
cout << "Enter first string: ";
cin >> str1;
cout << "Enter second string: ";
cin >> str2;
cout << "\nProcess of finding Longest Common Substring:" << endl;
longestCommonSubstring(str1, str2);
return 0;
}
INPUT AND OUTPUT: