The basic idea of the algorithm:
When the character matches, it is not simple to assign 1 to the corresponding element, but to assign the value of the upper-left corner element plus one.
We use two tag variables to mark the position of the element with the largest value in the matrix, in the process of matrix generation to determine
The value of the currently generated element is not the largest, thus changing the value of the tag variable, then to the completion of the matrix
, the position and length of the longest matched substring are already out.
===========================================================================
Program:
#include <string.h>
#define M 100
char* LCS (char Left[],char right[])
{//lcs problem is asking for the longest common substring of two strings
int Lenleft=strlen (left), Lenright=strlen (right), K;
Gets the length of the left substring, gets the length of the right substring
Char*c=malloc (lenright), *p;//Note that this is a char type instead of an int type, otherwise an error is generated when entering integer data. Matching of two strings in matrix C record
int Start,end,len,i,j;//start Indicates the starting point of the longest common substring, and end indicates the end point of the longest common string
End=len=0;//len indicates the length of the longest common substring
for (i=0;i<lenleft;i++)//String 1 comparison from front to back
{for (j=lenright-1;j>=0;j--)//String 2 comparison from backward forward
{if (left[i] = = Right[j])//When the element is equal
{if (i==0| | j==0)
C[j]=1;
Else
{c[j]=c[j-1]+1;
}
}
Else
C[J] = 0;
if (C[j] > Len)
{LEN=C[J];
End=j;
}
}
}
start=end-len+1;
p = (char*) malloc (len+1);//array p record longest common substring
for (I=start; i<=end;i++)
{P[i-start] = Right[i];
}
p[len]= ' + ';
return p;
}
void Main ()
{char str1[m],str2[m];
printf ("Please enter string 1:");
Gets (STR1);
printf ("Please enter string 2:");
Gets (STR2);
printf ("Oldest string:");
printf ("%s\n", LCS (STR1,STR2));
}
Problem with the longest common substring of two strings