字符串匹配的时间复杂度为O(n+m),返回的是匹配串在主串中的第一个位置
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
void get_next(string T,int *next)
{
int i,j;
i=1;
j=0;
next[0]=next[1]=0;
int len=T.size();
while(i<len)
{
if(j==0||T[i]==T[j])
{
++i;
++j;
next[i]=j;
}
else
j=next[j];
}
}
int kmp(string S,string T,int pos)
{
int i=pos;
int j=1;
int len1=S.size();
int len2=T.size();
int next[1000];
get_next(T,next);
while(i<=len1&&j<=len2)
{
if(j==0||S[i]==T[j-1])
{
++i;
++j;
}
else
j=next[j];
}
if(j>len2)
return i-len2+1;
else
return 0;
}
int main()
{
string S,T;
cin>>S>>T;
int res;
res=kmp(S,T,0);
cout<<res<<endl;
return 0;
}