题目描述
所谓最长公共子串,比如串A "acedfe", 串B "aede", 则它们的最长公共子串为串 "aede", 即不论串中字符是否相邻,只要它是给定各个串都包含的,且长度最长的串。给定两个不包含空格的字符串和一整数n , 如果最长公共串长度大于或等于n,输出Not Smaller, 否则输出Smaller.
输入要求
第一行仅一个整数N,(1<= N <= 100).表示包含N个测试样例. 每个测试样例由两个字符串A,B( 0< strlen(A),strlen(B) <= 1000) 和一个整数n( 0 <= n <= 1000)构成.
输出要求
对于每个测试样例,输出Not Smaller 或 Smaller.
输入样例
3
acedsd
acdd
2
eedfd
zzxxxx
3
feefs
as
1
输出样例
Not Smaller
Smaller
Not Smaller
思路分析
经典DP问题,需要注意的是在检索时要向四周检索最大子串
AC代码
#include<stdio.h>
#include<string.h>
#define MAX 1002
int DP[MAX][MAX];
char str1[MAX],str2[MAX];
int main()
{
int N,n,i,j;
scanf("%d",&N);
while(N--)
{
int max = 0;
memset(DP,0,sizeof(DP));
memset(str1,0,sizeof(str1));
memset(str2,0,sizeof(str2));//数组清零
scanf("%s",str1);
scanf("%s",str2);
scanf("%d",&n);//限定长度
for(i = 1;i <= strlen(str1); i++)
for(j = 1; j <= strlen(str2); j++)
{
if(str1[i - 1] == str2[j - 1])//依次比较
{
DP[i][j] = DP[i - 1][j - 1] + 1;//相连为相同
}
else//相连不为相同,向四周检索最大的
{
if(DP[i - 1][j] > DP[i][j - 1])
{
DP[i][j] = DP[i - 1][j];
}
else
{
DP[i][j] = DP[i][j - 1];
}
}
}
max = DP[strlen(str1)][strlen(str2)];//最长字串
if(max < n)
{
printf("Smaller\n");
}
else
{
printf("Not Smaller\n");
}
}
return 0;
}