KMP算法

KMP算法

#include<iostream>
#include<string.h>

using namespace std;


void Getnext(int* next, char*s)
{
    next[0] = -1;
    next[1] = 0;
    int i = 2;
    int k = 0;
    int lens = strlen(s);
    while (i < lens)
    {
        if ((k == -1) || (s[k]==s[i-1]))
        {
            next[i] = k + 1;
            i++;
            k++;
        }
        else
        {
            k = next[k];
        }
    }

}
int String_Seek(char* s, char* p,int pos)
{
    if (s == NULL && p == NULL)
    {
        cout << "string is error" << endl;
    }
    int lens = strlen(s);
    int lenp = strlen(p);
    if (lens < lenp)
    {
        cout << "string is illegal" << endl;
    }
    if (pos < 0 || pos > lens)
    {
        cout << "pos is error" << endl;
    }
    int i = pos;
    int j = 0;
    int *next = (int*)malloc(sizeof(int) * lens);
    if (next == NULL)
    {
        cout << " dynamic memory is error " << endl;
    }
    Getnext(next, s);
    cout << "  %d:  ";
    for (int m = 0; m < lens; m++)
    {
        cout << "  " << next[i];
    }
    cout << endl;
 
    while (i < lens && j < lenp)
    {
        if (j == -1 || s[i] == p[j])
        {
            i++;
            j++;
        }
        else
        {
            j = next[j];
        }
    }
    if (j >= lenp)
    {
        return i - j;
    }
    else
    {
        return -1;
    }
    free(next);
}
int main()
{
    char *s = "abcabcddhfabcdabc";
    char* p = "abcd";
    cout << "匹配的位置:" << String_Seek(s, p, 0) << endl;

    char *s1= "abcabcddhfabcdabc";
    char* p1= "abcd";
    cout << "匹配的位置:" << String_Seek(s1,p1,12)<< endl;

    char *s2 = "abcddhfabcdabc";
    char* p2 = "abcd";
    cout << "匹配的位置:" << String_Seek(s2, p2, 0) << endl;

    char *s3 = "abcababcabcabc";
    char* p3 = "abcabc";
    printf(" 相等的位置:   %d\n", String_Seek(s3, p3, 0));

    char *s4 = "abcababcabcabc";
    char* p4 = "abcababcabcabc";
    printf(" 相等的位置:   %d\n", String_Seek(s4, p4, 0));
        return 0;
}