KMP Algorithm and Implementation

#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<string>
#include<stack>
#include<queue>
#include<map>
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
int nextVal[1000];
//The next array is the substring of the substring s[0...i]
 // the subscript of the last bit of the prefix of the longest equal prefix and suffix
 // nextVal: When the i+1 bit of the pattern string is mismatched, i should fall back To the best position 
void getNextval( char s[], int len){
     int j=- 1 ;
    nextVal[0]=-1;//没有即为-1
    for(int i=1;i<len;i++){
        while(j!=-1&&s[i]!=s[j+1]){
            j=nextVal[j];
        }
        if(s[i]==s[j+1]){
            j++;
        }
        if(j==-1||s[i+1]!=s[j+1]){
            nextVal[i]=j;
        }else{
            nextVal[i]=nextVal[j];
        }
    }
}
// text text string, pattern pattern string 
int KMP( char text[], char pattern[]){
     int text_len= strlen(text);
     int pa_len= strlen(pattern);
    getNextval (pattern, pa_len);
    int ans=0,j=-1;
    for(int i=0;i<text_len;i++){
        while(j!=-1&&text[i]!=pattern[j+1]){
            j=nextVal[j];
        }
        if(text[i]==pattern[j+1]){
            j++;
        }
        // pattern matches exactly, indicating that pattern is a text substring 
        if (j==pa_len- 1 ){
            ans ++; // Number of successful matches+1 
            j= nextVal[j];
        }
    }
    return ans;
}
int main(){
    char text[10]="abababab";
    char pattern[10]="ababa";
    int ans=KMP(text,pattern);
    cout<<ans<<endl;
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324687751&siteId=291194637