数据结构实验之串一:KMP简单应用
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
给定两个字符串string1和string2,判断string2是否为string1的子串。
输入
输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。
输出
对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。
示例输入
abc a 123456 45 abc ddd
示例输出
1 4 -1
提示
来源
cjx
示例程序
解法一:
#include<stdio.h>
#include<string.h>
char a[10000010],b[1000010];
int next[1000010],n,m;
void Next()
{
next[0]=-1;
for(int j=1;j<m;j++)
{
int i=next[j-1];
while(b[j]!=b[i+1]&&i>=0)
{
i=next[i];
}
if(b[j]==b[i+1])
{
next[j]=i+1;
}
else
next[j]=-1;
}
}
int KMP()
{
Next();
int p=0,s=0;
while(p<m&&s<n)
{
if(a[s]==b[p])
{
s++;
p++;
}
else
{
if(p==0)
s++;
else
p=next[p-1]+1;
}
}
if(p<m)
return -1;
else
return s-m+1;
}
int main()
{
int i,j,k,t;
while(scanf("%s",a)!=EOF)
{
scanf("%s",b);
n=strlen(a);
m=strlen(b);
k=KMP();
printf("%d\n",k);
}
}
解法二:
#include<stdio.h>
#include<string.h>
char a[1000010],b[1000010];
int next[1000010],n,m;
void get_next(char T[],int next[])
{
int i=0;
next[0]=-1;
int j=-1;
while(i<m-1)
{
if(j==-1||T[i]==T[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int Index_KMP(char S[],char T[])
{
int i=0,j=0;
while(i<n&&j<m)
{
if(j==-1||S[i]==T[j])
{
i++;
j++;
}
else
j=next[j];
}
if(j>=m)
return i-m+1;
else
return -1;
}
int main()
{
int i,j,k,t;
while(scanf("%s",a)!=EOF)
{
scanf("%s",b);
n=strlen(a);
m=strlen(b);
get_next(b,next);
k=Index_KMP(a,b);
printf("%d\n",k);
}
}