这个需要用到动态规划的算法,这是程序:(这个程序不是我写的呀,是我同学写的呀!嘻嘻)
# include <stdio.h>
# include<string.h>
# include <stdlib.h>
#define M 100
char* LCS(char left[] , char right[])
{
int lenLeft = strlen(left) , lenRight = strlen(right) ;
char *c = malloc(lenRight) , *p ;
int start , end , len , i , j ;
end = len = 0;
for(i = 0 ; i < lenLeft ; i++)
for(j = lenRight - 1 ; j >= 0 ; j--)
{
if(left[i] == right[j])
{
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) ;
for(i = start ; i<= end ; i++)
p[i-start] = right[i] ;
p[len] = '\0' ;
return p;
}
int main()
{
char str1[M] , str2[M] ;
printf("请输入字符串1:") ;
gets(str1) ;
printf("请输入字符串2:") ;
gets(str2) ;
printf("最长子串为:") ;
printf("%s\n",LCS(str1,str2)) ;
return 0 ;
}