拓展KMP 模板

    技术2022-05-20  55

    #include <iostream>

    #include <cstdio>

    #include <cstring>

    using namespace std;

    //拓展KMP GetExtend(str, strlen(str), extend, mode, strlen(mode));

    //str 主串  mode 模式串 int extend[maxn];/[0,len)

    void GetExtendNext(const char *mode, int *next, const int strlen)

    {

        int a, p, j = -1;

        next[0] = 0;

        for (int i = 1; i < strlen; i++,j--)

        {

            if (j < 0 || i + next[i - a] >= p)

            {

                if (j < 0) j = 0, p = i;

                while (p < strlen && mode[p] == mode[j])

                    ++p, ++j;

                next[i] = j, a = i;

            }

            else next[i] = next[i - a];

        }

    }

     

    void GetExtend(const char *str, const int strlen, int *extend, const char *mode, const int modeLen)

    {

        int *next = new int[modeLen];

        GetExtendNext(mode, next, modeLen);

        int a, p, j = -1;

        for (int i = 0; i < strlen; i++,--j)

        {

            if (j < 0 || i + next[i - a] >= p)

            {

                if (j < 0) j = 0, p = i;

                while (p < strlen && j < modeLen && str[p] == mode[j])

                    ++p, ++j;

                extend[i] = j, a = i;

            }

            else extend[i] = next[i - a];

        }

        delete []next;

    }

     

    int main()

    {

        int extend[120];

        GetExtend(str, strlen(str), extend, mode, strlen(mode));

        return 0;

    }


    最新回复(0)