KMP字符串匹配

来源:互联网 发布:金融数据挖掘 pdf 编辑:程序博客网 时间:2024/05/23 19:53

#include<iostream>#include<cstdio>#include<cstring>using namespace std;void creatNext(char* str,int* next,int len){    next[0]=0;    for(int i=1;i<len;i++)    {        if(str[next[i-1]]==str[i])        {            next[i]=next[i-1]+1;        }        else        {            next[i]=0;        }    }}int kmp(char* str,char* sub_str){    int i=0;    int str_Len=strlen(str);    int substr_Len=strlen(sub_str);    int sunstrStartIndex=0;    int next[substr_Len];    creatNext(sub_str,next,substr_Len);    while(1)    {        while(sunstrStartIndex<substr_Len&&i<str_Len&&sub_str[sunstrStartIndex]==str[i])        {            sunstrStartIndex++;            i++;        }        if(sunstrStartIndex==substr_Len)        {            return i-substr_Len;        }        else if(i==str_Len)        {            return -1;        }        else        {            if(sunstrStartIndex==0) i++;            else            {                sunstrStartIndex=next[sunstrStartIndex-1];            }        }    }}int main(){    char* str="BBC ABCDAB ABCDABCDABDE";    char* sub_str="ABCDABD";//    char* str="aaac";//    char* sub_str="aaaaaaa";    int result=kmp(str,sub_str);    cout<<result<<endl;}


0 0
原创粉丝点击