最长公共子串
发布时间: 2015年12月17日 09:41 最后更新: 2015年12月29日 20:04 时间限制: 1000ms 内存限制: 128M
编写一个程序,求两个字符串的最长公共子串。输出两个字符串的长度,输出他们的最长公共子串及子串长度。如果有多个最长公共子串请输出在第一个字符串中先出现的那一个。
特别注意公共子串中可能包含有空格,但不计回车符!
两个字符串,回车结尾,每个字符串中都可能含有空格(每个字符串的长度不超过200个字符)
一共有四行,前两行以Length of String1:和Length of String2:开始冒号后面分别输出两字符串的长度。
第三行Maxsubstring:输出符合题目里描述的子串。第四行是Length of Maxsubstring:加子串长度。注意!冒号后面不要输出多余的空格!
复制
this is a string my string is abc
Length of String1:16 Length of String2:16 Maxsubstring: string Length of Maxsubstring:7
复制
abcdef defabc
Length of String1:6 Length of String2:6 Maxsubstring:abc Length of Maxsubstring:3
复制
aabbcc aabbcc
Length of String1:6 Length of String2:6 Maxsubstring:aabbcc Length of Maxsubstring:6
#include<stdio.h>
#include<string.h>
int main()
{
char str1[205]={0},str2[205]={0};
int len1,len2,ans=0,ansi=0,ansj=0,dp[205][205]={0};
gets(str1);
gets(str2);
len1=strlen(str1);
len2=strlen(str2);
printf("Length of String1:%d\n",len1);
printf("Length of String2:%d\n",len2);
for(int i=0;i<len1;i++)
{
for(int j=0;j<len2;j++)
{
if(str1[i]==str2[j])
dp[i+1][j+1]=dp[i][j]+1;
if(dp[i+1][j+1]>ans)
{
ans=dp[i+1][j+1];
ansi=i+1;
}
else if(dp[i+1][j+1]==ans)
{
if(i+1<ansi)
ansi=i+1;
}
}
}
printf("Maxsubstring:");
for(int i=ansi-ans;i<=ansi-1;i++)
{
printf("%c",str1[i]);
}
putchar('\n');
printf("Length of Maxsubstring:%d",ans);
return 0;
}