美文网首页
【扩展kmp】扩展kmp及i+next[i-a]分析

【扩展kmp】扩展kmp及i+next[i-a]分析

作者: jenye_ | 来源:发表于2018-08-06 15:30 被阅读0次

【扩展KMP参考】: 扩展KMP算法-刘毅

上文对于扩展kmp的分析很详细,解释的很清晰。但在文中写的i+next[i-a]是否能大于p写到:

如果i+next[i-a]>=p呢?很容易发现i+next[i-a]是不可能大于p的。

但在代码中,对大于p的情况做了限制:

困扰了我很久。


分析扩展kmp i+next[i-a] 大于p的情况。

  • 如果考虑不可能大于p的情况:

    去掉上段代码的限制。样例:"aaaaac",得到的next数组如下:

    显然是错误的。

  • 什么情况下会出现i+next[i+a]大于p的情况

    这里以"aaaaaa" 为例:

    我们在计算next[2]时,需要用到next[1],而显然next[1]的前缀长度,包括了未参与匹配的a,而目标串的对应位置已经超出了字符串长度,所以才会出现大于长度p的情况。而对于这种情况,原文才对大于p的情况做了限制,从新计算next[2],而不用next[2-1]参与。

参考代码

/**
 *
 * author 刘毅(Limer)
 * date   2017-03-12
 * mode   C++
 */
#include<iostream>
#include<string>
using namespace std;

/* 求解T中next[],注释参考GetExtend() */
void GetNext(string T, int next[])
{
    int t_len = T.size();
    next[0] = t_len;
    int a;
    int p;

    for (int i = 1, j = -1; i < t_len; i++, j--)
    {
        if (j < 0 || i + next[i - a] >= p)
        {
            if (j < 0)
                p = i, j = 0;

            while (p < t_len&&T[p] == T[j])
                p++, j++;

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

/* 求解extend[] */
void GetExtend(string S, string T, int extend[], int next[])
{
    GetNext(T, next);  //得到next
    int a;             
    int p;             //记录匹配成功的字符的最远位置p,及起始位置a
    int s_len = S.size();
    int t_len = T.size();

    for (int i = 0, j = -1; i < s_len; i++, j--)  //j即等于p与i的距离,其作用是判断i是否大于p(如果j<0,则i大于p)
    {
        if (j < 0 || i + next[i - a] >= p)  //i大于p(其实j最小只可以到-1,j<0的写法方便读者理解程序),
        {                                   //或者可以继续比较(之所以使用大于等于而不用等于也是为了方便读者理解程序)
            if (j < 0)
                p = i, j = 0;  //如果i大于p

            while (p < s_len&&j < t_len&&S[p] == T[j])
                p++, j++;

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

int main()
{
    int next[100] = { 0 };
    int extend[100] = { 0 };
    string S = "aaaaabbb";
    string T = "aaaaac";

    GetExtend(S, T, extend, next);

    //打印next和extend
    cout << "next:    " << endl;
    for (int i = 0; i < T.size(); i++)
        cout << next[i] << " ";

    cout << "\nextend:  " << endl;
    for (int i = 0; i < S.size(); i++)
        cout << extend[i] << " ";

    cout << endl;
    return 0;
}

相关文章

网友评论

      本文标题:【扩展kmp】扩展kmp及i+next[i-a]分析

      本文链接:https://www.haomeiwen.com/subject/ryqgvftx.html