KMP算法

正确的如下:

#include
#include
#include
using namespace std;
int* getNext(string duan)//和下面的函数顺序不能写反!!!
{
    int length_d = duan.length();
    int* next = (int*)calloc(length_d, sizeof(int));
    next[0] = -1;
    int c = 0, d = -1;
    while (c < length_d - 1)//当while里面c=length_d-2时,if{}里面next[length_d-1]已经算好了;当while里面c=length_d-1时,if{}里面的c满足退出条件
    {
        if (-1 == d || duan[c] == duan[d])
        {
            c++;
            d++;
            next[c] = (duan[c] != duan[d] ? d : next[d]);
        }
        else
            d = next[d];
    }
    return next;
}
int IndexKmp(string chang, string duan)
{
    int* next = getNext(duan);
    int c = 0, d = 0;
    int length_c = chang.length(), length_d = duan.length();
    while (c < length_c && d < length_d)
    {
        if (-1 == d || chang[c] == duan[d])
        {
            c++;
            d++;
        }
        else
            d = next[d];
    }
    free(next);
    return length_d == d ? c - d : -1;
}
int main()
{
    string chang ,duan ;
    int i;
    cout << "输入主字符串:";
    cin >> chang ;
    cout << "输入匹配的短字符串:";
    cin >> duan;
    cout << IndexKmp(chang, duan);
    return 0;
}

image.png

和下面错误的区别就是一个头文件cstring(不是点)、string和char*、length()和strlen
错误的如下,日后解决,现在不会

#include
#include
using namespace std;
int* getNext(char* duan)
{
    int length_d = strlen(duan);
    int* next = (int*)calloc(length_d, sizeof(int));
    next[0] = -1;
    int c = 0, d = -1;
    while (c < length_d - 1)
    {
        if (-1 == d || duan[c] == duan[d])
        {
            c++;
            d++;
            next[c] = (duan[c] != duan[d] ? d : next[d]);
        }
        else
            d = next[d];
    }
    return next;
}
int IndexKmp(char* chang, char* duan)
{
    int* next = getNext(duan);
    int c = 0, d = 0;
    int length_c = strlen(chang), length_d = strlen(duan);
    while (c < length_c && d < length_d)
    {
        if (-1 == d || chang[c] == duan[d])
        {
            c++;
            d++;
        }
        else
            d = next[d];
    }
    free(next);
    return length_d == d ? c - d : -1;
}
int main()
{
    char chang[10], duan[5];
    int i;
    cout << "输入主字符串:";
    cin >> chang;
    cout << "输入匹配的短字符串:";
    cin >> duan;
    cout << IndexKmp(chang, duan);
    return 0;
}

答案和正确的一样,但是程序会蹦出一个bug:
image.png

你可能感兴趣的:(KMP算法)