题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2594
题解:finds the longest prefix of s1 that is a suffix of s2. s1作为模式串 s2作为原串,进行KMP
#include <stdio.h>
#include <string.h>
#define MAXN 50002
int next[MAXN],len1,len2;
char str1[MAXN],str2[MAXN];
void getNext()
{
int i=0,j=-1;
next[0]=-1;
while(i<len2)
{
if (j==-1||str2[i]==str2[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int KMP()
{
int i,j;
i=j=0;
getNext();
while(i<len1&&j<=len2)
{
if(j==-1||str1[i]==str2[j])
{
i++;
j++;
}
else
j=next[j];
}
return j;
}
int main()
{
int n,i;
while (scanf("%s %s",str2,str1)!=EOF)
{
len1=strlen(str1);
len2=strlen(str2);
n=KMP();
if(n==0)
printf("0\n");
else
{
for(i=0;i<n;++i)
printf("%c",str2[i]);
printf(" %d\n",n);
}
}
return 0;
}
本文介绍了一种使用KMP算法寻找两个字符串间最长前缀匹配的方法。通过实例演示了如何实现KMP算法,并提供了完整的C语言代码。适用于需要解决字符串匹配问题的开发者。
812

被折叠的 条评论
为什么被折叠?



