分析:
- KMP模板
- 首先读入两个字符串 s1 和 s2,并计算它们的长度 m 和 n。然后调用 getn 函数来计算 s2 字符串的 next 数组。接着使用 KMP 算法在 s1 中查找 s2 的出现位置,并输出匹配的起始位置。
- 在 getn 函数中,计算了 s2 字符串的 next 数组,用于在 KMP 算法中进行匹配时的跳转。在主函数中,利用 next 数组来进行匹配,找到所有 s2 在 s1 中的出现位置,并输出。
代码:
#include <stdio.h>
#include <string.h>
char s1[1000001],s2[1000001];
int next[1000001],m,n;
void getn()
{
int i=1,j=0;
next[0]=0;
for(int i=1;i<n;i++)
{
while(j>0&&s2[i]!=s2[j])
{
j=next[j-1];
}
if (s2[i]==s2[j])
j++;
next[i]=j;
}
}
int main()
{
scanf("%s%s",s1,s2);
m=strlen(s1),n=strlen(s2);
getn();
int j=0;
for(int i=0;i<m;i++)
{
while(j>0&&s1[i]!=s2[j])
{
j=next[j-1];
}
if(s1[i]==s2[j])
j++;
if(j==n)
printf("%d\n",i-n+2);
}
for(int i=0;i<n;i++)
printf("%d ",next[i]);
return 0;
}