Problem Description:
Given two sequences x=<x1, x2, ..., xm>, y<y1, Y2, ..., yn>, find the common substring of X and Y longest length. ( the characters in the substring require continuous )
This problem is similar to the longest common subsequence (longest common subsequence) and can also be defined with dynamic programming. The formula is as follows:
Here C[i,j] represents the length of the longest common substring ending with xi,yj.
Program implementation:
intLongestcommonsubstring (stringXstringy) { intm =x.length (); intn =y.length (); Vector< vector<int> > C (m+1, vector<int> (n+1)); for(inti =0; I <= m; ++i) c[i][0] =0; for(intj =1; J <= N; ++j) c[0][J] =0; intLen =0; for(inti =1; I <= m; ++i) { for(intj =1; J <= N; ++j) {if(x[i-1] = = y[j-1]) {C[i][j]= c[i-1][j-1] +1; if(C[i][j] >len) Len=C[i][j]; ElseC[i][j]=0; } } returnLen;}
Reference
Algorithm design-LCS longest common subsequence && longest common substring &&lis longest increment subsequence Huawei oj2011-longest common substring
Longest common substring (longest common substring)