Here is the program for longest common substring for given two strings.
// LongestCommonSubstring.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "string.h"
void LongCommSubstring();
void PrintLongCommonSubstring();
char String1[100];
char String2[100];
int a[100][100];
int b[100][100];
int _tmain(int argc, _TCHAR* argv[])
{
char ch;
printf("Enter the String Number 1:-");
scanf("%s", String1);
printf("\nEnter the String Number 2:-");
scanf("%s",String2);
LongCommSubstring();
PrintLongCommonSubstring();
fflush(stdin);
scanf("%c",&ch);
return 0;
}
void LongCommSubstring()
{
int m = strlen(String1);
int n = strlen(String2);
for (int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
{
if(String1[i-1] == String2[j-1])
{
a[i][j] = a[i-1][j-1] + 1;
}
else
a[i][j]=0;
}
}
void PrintLongCommonSubstring()
{
int m = strlen(String1);
int n = strlen(String2);
int MaxLength = 0;
int MaxIndex_i =0, MaxIndex_j = 0;
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
{
if(a[i][j] > MaxLength)
{
MaxIndex_i = i;
MaxIndex_j = j;
MaxLength = a[i][j];
}
}
printf("Length of Longest Common Substring is ....%d\n",MaxLength);
printf("Longest Common Substring is...\n");
for(int i=MaxIndex_i - MaxLength + 1,j = MaxIndex_j - MaxLength + 1;
i<=MaxIndex_i && j <= MaxIndex_j ;i++,j++)
{
printf("%c",String1[i-1]);
}
}
No comments:
Post a Comment