Review -KMP algorithm

KMP algorithm for learning, in the winter I still do not quite understand, but after a few months, for its understanding and a step closer.

The first is self-aligned to the substrings, seeking a array fail, fail [i] for the string S before the S i substrings constituting the i-th character, both its suffix string is its prefix (itself excluded), referred to as the longest length Fail [ I ] .

For example, the values ​​abcdabc fail [7] is 3. When we mismatch, it jumps directly to fail [i] the value referred to, so that efficiency is a big upgrade.

Similarly, the sub pattern matching is string and this routine. For explain KMP algorithm, it is recommended to have a video of Indians still speak more clearly on the go bilibili.

Code

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e7+7;
int fail[maxn],show[maxn];
char s1[maxn],s2[maxn];
int ans;
int len1,len2;
int j;
void getfail(){
    fail[1]=0;
    for(int i=2;i<=len2;i++){
        while(j!=0&&s2[i]!=s2[j+1]) j=fail[j];
        if(s2[i]==s2[j+1]) j++;
        fail[i]=j;
    }
} 
void kmp(){
    J = 0 ;
     for ( int I = . 1 ; I <= LEN1; I ++ ) {
         the while (J =! 0 && S1 [I] = S2 [J +! . 1 ]) J = Fail [J];
         IF (S1 [I] S2 == [J + . 1 ]) J ++; // letter string does not move, move their substring 
        IF (J == LEN2) {
            years ++ ;
            Show [ANS] = I +-LEN2 . 1 ; // Qiuzi string to appear 
        }
    }
}
int main () {
    scanf("%s%s",s1+1,s2+1);
    len1=strlen(s1+1);
    len2=strlen(s2+1);    
    getfail();
    sq ();
    for(int i=1;i<=ans;i++){
        printf("%d\n",show[i]);
    }
    for(int i=1;i<=len2;i++){
        printf("%d ",fail[i]);
    }
    return 0;
}

 

Reproduced in: https: //www.cnblogs.com/LJB666/p/11026729.html

Guess you like

Origin blog.csdn.net/weixin_34384915/article/details/93223583