# Problem with the longest common substring of two strings

Source: Internet
Author: User

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];
Gets (STR1);
Gets (STR2);
printf ("Oldest string:");
printf ("%s\n", LCS (STR1,STR2));
}

Problem with the longest common substring of two strings

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.