Extended KMP (Template)

Extending KMP is an extension of KMP algorithm. It solves the following problems:
Define the parent string S, and the string T. Let the length of S be n and the length of T be m. Find the longest common prefix for each suffix of T and S. That is to say, set an extended array, extend[i] denotes the longest common prefix for T and S[i,n-1], and require all extend[i] (0<=i<n).
Note that if there is a location extend[i]=m, it means that T appears in S and in position i, which is the standard KMP problem, so extended KMP is an extension of KMP algorithm, so it is generally called extended KMP algorithm.

const int MAXN=100000;
int next[MAXN];
int extend[MAXN];
void getNext(char *str)
{
    int len=strlen(str),p0,i=0,j;
    next[0]=len;//Initialize next [0]
    while(str[i]==str[i+1]&&i+1<len) i++;
    next[1]=i;
    p0=1;//Initialize p0
    for(i=2;i<len;i++)
    {
        if(next[i-p0]+i<next[p0]+p0) next[i]=next[i-p0];//In the first case, the value of next[i] can be obtained directly.
        else//In the second case, the value of next[i] can only be obtained by continuing to match  
        {
            j=next[p0]+p0-i;//If I > Po + next [po], match from scratch
            if(j<0) j=0;
            while(i+j<len&&str[i+j]==str[j]) j++;//Computing next[i]
            next[i]=j;
            p0=i;
        }
    }
}
void exkmp(char *str,char *p)//Compute the extend ed array 
{
    int i=0,j,p0,slen=strlen(str),plen=strlen(p);
    getNext(p);//next array for calculating p
    while(i<slen&&i<plen&&str[i]==p[i]) i++;//Calculate ex[0]  
    extend[0]=i;
    p0=0;//Initialize the location of po  
    for(i=1;i<slen;i++)
    {
        if(next[i-p0]+i<extend[p0]+p0) extend[i]=next[i-p0];//In the first case, the value of ex[i] can be obtained directly.
        else //In the second case, the value of ex[i] can only be obtained by continuing to match  
        {
            j=extend[p0]+p0-i;
            if(j<0) j=0;//If I > ex [po] + po, match from scratch
            while(i+j<slen&&j<plen&&str[i+j]==p[j]) j++;//Calculate ex[i]
            extend[i]=j;
            p0=i;//Update the location of po  
        }
    }
}``

Posted by Tensing on Sat, 05 Oct 2019 07:30:18 -0700