首页 > 代码库 > kmp算法代码

kmp算法代码

 

#include<iostream>#include<string>#include<cstring>using namespace std;const int maxsize=100;void getnext(string t,int next[]){	int j,k;	j=0; k=-1; next[0]=-1;	while(j<int (t.length())-1)	{		if(k==-1 ||t[j]==t[k])		{			j++;k++;			next[j]=k;		}		else k=next[k];	}}int kmpindex(string s,string t){	int next[maxsize],i=0,j=0;	memset(next,-1,sizeof(next));	getnext(t,next);	while(i<int (s.length() )&&j<int (t.length() ))//需把unsigned int转换为 int	{		if(j==-1 ||s[i]==t[j])		{			i++;			j++;		}		else j=next[j];	}	if(j>=int (t.length() ))		return (i-int (t.length()));	else		return -1;}int main(){	string a;	string b;	cin>>a;	cin>>b;	cout<<kmpindex(a,b)<<endl;	return 0;}