KMP

#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;
}


你可能感兴趣的:(KMP)