题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1841
题解:1.s1是s2的子串,或者s2是s1的子串。2.s1是s2的前缀或者后缀。
#include <stdio.h>
#include <string.h>
#define MAXN 1000002
int next[MAXN];
char str1[MAXN],str2[MAXN];
void getNext(char *str,int len)
{
int i=0,j=-1;
next[0]=-1;
while(i<len)
{
if (j==-1||str[i]==str[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int KMP(char *str,char *pattern,int len1,int len2)
{
int i,j;
i=j=0;
getNext(pattern,len2);
while(i<len1&&j<len2)
{
if(j==-1||str[i]==pattern[j])
{
i++;
j++;
}
else
j=next[j];
}
if(j<=len2)
return j;
else
return -1;
}
int main()
{
int test,x,y,len1,len2;
scanf("%d",&test);
while (test--)
{
scanf("%s %s",str1,str2);
len1=strlen(str1);
len2=strlen(str2);
x=KMP(str1,str2,len1,len2);
y=KMP(str2,str1,len2,len1);
if(x>y)
printf("%d\n",len1+len2-x);
else
printf("%d\n",len1+len2-y);
}
return 0;
}