参考文章地址如下:http://blog.csdn.net/hackbuteer1/article/details/6686931
子字符串的定义和子序列的定义类似,但要求是连续分布在其他字符串中。比如输入两个字符串BDCABA和ABCBDAB的最长公共字符串有BD和AB,它们的长度都是2。
Substring可以用动态规划解决,令 c[i][j]表示Xi和Yi的最大Substring的长度,比如
X = <y, e, d, f>
Y = <y, e, k, f>
c[1][1] = 1
c[2][2] = 2
c[3][3] = 0
c[4][4] = 1
动态转移方程为:
如果xi == yj, 则 c[i][j] = c[i-1][j-1]+1
如果xi ! = yj, 那么c[i][j] = 0
代码如下:
#include <stdio.h>
#include <string.h>
int comm_str(char * str1, char * str2)
{
int i, j, k, max, x, y;
const int len1 = strlen(str1);
const int len2 = strlen(str2);
int c[len1][len2];
for(i = 0; i < len1+1; i++)
for(j = 0; j < len2+1; j++)
c[i][j] = 0;
max = -1;
for(i = 1; i < len1; i++)
{
k = 0;
for(j=1; j < len2; j++)
{
if(str1[i-1+k] == str2[j-1])
{
c[i+k][j]=c[i-1+k][j-1]+1;
if(c[i+k][j]>max)
{
max=c[i+k][j]; x=i+k; y=j;
}
k++;
}
else
c[i+k][j]=0;
}
}
char s[10000];
k=max;
i=x-1, j=y-1;
s[k--]='\0';
while(i>=0 && j>=0 && k >= 0)
{
if(str1[i]==str2[j])
{
s[k--]=str1[i]; i--; j--;
}
else
break;
}
printf("most longest common str:");
puts(s);
return max;
}
int main()
{
char str1[10000], str2[10000];
puts("please input first string:"); gets(str1);
puts("please input second string:"); gets(str2);
printf("the length of longest common substring is %d\n",comm_str(str1, str2));
}
执行结果如下: