Data structure KMP algorithm -- C language implementation

Keywords: Programming

To implement KMP algorithm, the first thing to solve is the next array. The essence of KMP algorithm lies in this point. However, Yan Weimin's data structure is not easy to understand at this point. Here is a video from station B. you can understand the working principle of KMP algorithm and the method of manually solving next array as a prerequisite.

https://www.bilibili.com/video/BV1jb411V78H?from=search&seid=975091333872042622

To understand and complete the above knowledge, the following is how to program to solve the next array of substrings. Note here that * * according to Yan Weimin's data structure, access to the default string starts from position 1, not position 0. **Let's focus on the programming principle of next array:


Make clear the solution of the next array above, and the subsequent code compilation problem will be solved

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAX 255

typedef struct
{
    char str[MAX+1];
    int length;
}SSteing;

void get_next(SSteing T,int next[]);
int KMP(SSteing S,SSteing T,int next[]);

int main(void)
{
    SSteing S,T;
    char a[MAX+1],b[MAX+1];
    int next[MAX+1];
    printf("Please enter the main string:");
    scanf("%s",a);
    printf("Please enter a string:");
    scanf("%s",b);
    S.length = strlen(a);
    T.length = strlen(b);
    for(int i = 1;i < S.length+1;i++)
    {
        S.str[i] = a[i-1];
    }
    for(int i = 1;i < T.length+1;i++)
    {
        T.str[i] = b[i-1];
    }
    get_next(T,next);
    KMP(S,T,next);
    if(KMP(S,T,next))
    {
        printf("Match succeeded! The starting position is:%d\n",KMP(S,T,next));
    }
    else
    {
        printf("Matching failed!\n");
    }
    system("pause");
    return 0;
}

void get_next(SSteing T,int next[])
{
    int j = 1,t = 0;
    next[1] = 0;
    while (j < T.length)
    {
        if(t == 0 || T.str[j] == T.str[t])
        {
            j++;
            t++;
            next[j] = t; 
        }
        else
        {
            t = next[t];
        }
    }
    printf("Of the string next The array is:");
    for(int i = 1;i < T.length + 1;i++)
    {
        printf("%d ",next[i]);
    }
    printf("\n");
}

int KMP(SSteing S,SSteing T,int next[])
{
    int i = 1,j = 1;
    while (i <= S.length && j <= T.length)
    {
        if(j == 0 || S.str[i] == T.str[j])
        {
            i++;
            j++;
        }
        else
        {
            j = next[j];
        }
    }
    if(j > T.length)
    {
        return i - T.length;
    }
    else
    {
        return 0;
    }
}

If you have any questions or opinions, please chat with me or email 1308269670@qq.com Contact me.

Posted by ca87 on Thu, 04 Jun 2020 07:42:29 -0700