KMP算法

来源:互联网 发布:阿里云邮箱 编辑:程序博客网 时间:2024/05/16 19:38
#include<iostream>
#include<assert.h>
using namespace std;
void getNext(const char* str,int next[])//获取next数组
{
assert(str!=NULL&&next!=NULL);
int i=1,j=0;
int len=strlen(str);
next[0]=0;
next[1]=1;
while(i<len)
{
if(j==0||str[i]==str[j-1])
{
++i;
++j;
next[i]=j;
}
else
j=next[j-1];
}
}


int kmp(const char *str,const char *des,int *next)//kmp字符串匹配
{
assert(str!=NULL&&des!=NULL&&next!=NULL);
int m=strlen(str);
int n=strlen(des);
int i=0,j=0;
while(i<m&&j<n)
{
if(j==0||str[i]==des[j])
{
if(str[i]==des[j])
{
i++;
j++;
}
else
i++;
}
else
j=next[j-1];
}
if(j>=n)
return i-n;
else
return -1;
}
int main()
{
char sub[]="abaabcac";
int length=strlen(sub);
int *p=new int[length];
char str[]="ccccabaabcaccc";
int data=kmp(str,sub,p);
cout<<data<<endl;
system("pause");
}
0 0