#include<iostream>
using namespace std;
void fail(int *f,int n,char * substr)//失败函数
{
if(n==0)
return ;
f[0]=-1;
for(int j=1;j<n;j++)
{
int i = f[j-1];
while(substr[j] != substr[i+1]&&i>=0)//此处是失败函数的关键,找不到就回退
i = f[i];
if(substr[j] == substr[i+1])
f[j] = i+1;
else
f[j] = -1;
}
for(int i = 0;i<n;i++)
{
cout<<f[i]<<" ";
}
cout<<endl;
}
int KMP(char * str,int len,char * substr,int sub_len)
{
if(len<=sub_len||len<=0||sub_len<=0)
return -1;
int * f = new int[sub_len];
fail(f,sub_len,substr);
int j=0;
int i=0;
while(j<sub_len&&i<len)
{
if(str[i]==substr[j])
{
i++;
j++;
}
else
{
if(j==0)
i++;
else
{
j=f[j-1]+1;
}
}
}
if(j<sub_len)
return -1;
else
return i-sub_len;
}
int main()
{
char test[]="abcdefdefghij";
char sub[]="defdef";
int i = KMP(test,13,sub,6);
cout<<i<<endl;
return 0;
}
KMP算法
最新推荐文章于 2022-11-03 21:50:23 发布