/**********************************************
*@2016/08/26 13:54
*@place ctrip.15#.9F
*****************************************************/
#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAX_LENGTH 1000
/***************************************************************************************************
*@name get_SubString 得到两个字符串的最大子串
*@parameter char* str1,int len1,char *str2,int len2 俩个字符串及其长度
*@description 利用动态规划的方法打印出最大公共子串
**********************************************************************************************************/
void get_SubString(char* str1,int len1,char *str2,int len2)
{
int dp[len1+1][len2+1];
for(int i=0;i<=len1;i++)//初始化
{
for(int j=0;j<=len2;j++)
{
dp[i][j]=0;
}
}
int max_subString_Length=-1;//最大公共子串的长度
int last_Index=-1;//公共子串的下标
for(int i=1;i<=len1;i++)
{
for(int j=1;j<=len2;j++)
{
if(str1[i-1]==str2[j-1])
{
dp[i][j]=dp[i-1][j-1]+1;
if(dp[i][j]>max_subString_Length)
{
max_subString_Length=dp[i][j];
last_Index=i-1;
}
}
else
{
dp[i][j]=0;
}
}
}
printf("The length of substring=%d\n",max_subString_Length);
for(int i=last_Index-max_subString_Length+1;i<=last_Index;i++)//打印
{
printf("%c",str1[i]);
}
}
int main()
{
char str1[MAX_LENGTH];
char str2[MAX_LENGTH];
printf("Please input two strings\n");
scanf(" %s %s",str1,str2);
int len1=strlen(str1);
int len2=strlen(str2);
get_SubString(str1,len1,str2,len2);
}
最长公共子串
最新推荐文章于 2024-05-15 21:19:25 发布