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
a
123456
45
abc
ddd
输出:
1
4
-1
模板题
#include <iostream>
#include <cstring>
using namespace std;
char s1[1000000],s2[1000000];
int next[1000000];//不能在函数里面定义局部变量为一百万,可以是10万 有关解析:
//http://www.ljsq.net/read/3c-2b-2b-c8-e7-ba-ce-b6-a8-d2-e5-d2-bb-b8-f6-b3-a4-b6-c8-b3-ac-b9-fd-d2-bb-b0-d9-cd-f2-b5-c4-ca-fd-d7-e9.html
int main()
{
// char s1[1000000],s2[1000000];
// int next[1000000];
while(cin>>s1)
{
cin>>s2;
int k=-1,j=0;
next[0]=-1;
while(j<strlen(s2)-1)
{
if(k==-1||s2[j]==s2[k])
{
j++,k++;
next[j]=k;
}
else
k=next[k];
}
int i=0;
j=0;
while(j<strlen(s2)&&i<strlen(s1))
{
if(s1[i]==s2[j]||j==0)
{
i++;
j++;
}
else
j=next[j];
}
// cout<<i<<endl;
if(j>=strlen(s2))
cout<<i+1-strlen(s2)<<endl;
else
cout<<"-1"<<endl;
}
return 0;
}
这个连接是学习中看的关于KMP的讲解:
http://blog.csdn.net/yutianzuijin/article/details/11954939/
http://blog.csdn.net/v_july_v/article/details/7041827
求解kmp next的另一方法:
int getnext()
{
int next[maxn];
next[0]=-1;
next[1]=0;
int s=str2.length();
int i=2;
int cn=0;
while(i<s)
{
if(str[i-1]==str[cn])
{
next[i++]=++cn;
}
else if(cn>0)//cn>=0
cn=next[cn];
else
next[i++]=0;
}
}