KMP

来源:互联网 发布:微信红包埋雷开挂软件 编辑:程序博客网 时间:2024/05/16 12:13
#include<iostream>#include<string.h>using namespace std;int *GetNext(char *str){    if(str == NULL)    {        return NULL;    }    int *next = new int[strlen(str)];    int i = 1;    int ID = i-1;    next[0] = 0;    while(str[i]!= '\0')    {        if(str[i] == str[next[ID]])        {            next[i] = next[ID] + 1;            i++;            ID = i-1;            continue;        }        if(next[ID] == 0)        {            next[i] = 0;            i++;            ID = i-1;            continue;        }        ID = next[ID] - 1;    }    return next;}int KMP(char *str1,char *str2){    int *next = GetNext(str2);    int i = 0;    int j = 0;    while(str1[i] != '\0')    {        if(str1[i] == str2[j])        {            i++;            j++;            if(str2[j] == '\0')            {                return i-j;            }        }        else        {            if(j==0)            {                i++;            }            else            {                j = next[j-1];            }        }    }    return -1;}int main(){    char *str = "abcdaabcdaaabcdcdcdbabcddffff";    int *next = GetNext(str);    for(int i=0;i<strlen( "abcdaabcdaaabcdcdcdbabcddffff");i++)    {        cout<<next[i]<<" ";    }    cout<<endl;    cout<<KMP("abcdaabcdaaabcdcdcdbabcddffff","ddd")<<endl;    return 0;}


1 0
原创粉丝点击