Single Pattern Matching KMP-

pat schematic sequence, txt represents a text string, nex [i] denotes the front pat of 0 ~ (i-1) the longest common suffix.

The number or location of KMP seek pat appeared in txt. nex fail string array pointer mode ac similar automatic machine, when a mismatch occurs, the jump position has the same prefix matching the longest suffix. Nex process of seeking an array of self-matching process is pat.

Learning Link: Portal   different conventions attention to this blog article scheduled conventions and codes

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int maxn=1e6+7;
char str[maxn];
struct kmp{
    char  pat[maxn];
    int pat_len;
    int nex[maxn];
    void GetNext(){
        int i=0,j=-1;
        pat_len=strlen(pat);
        nex[0]=-1;
        while(i<pat_len){
            while(j!=-1&&pat[i]!=pat[j]) j=nex[j];
            nex[++i]=++j;
        }
    }
    int Count(char *txt){///返回模式串在主串中出现的次数(可重叠出现)
        int txt_len=strlen(txt),i=0,j=0,cnt=0;
        while(i<txt_len){
            if(j!=-1&&txt[i]!=pat[j]) j=nex[j];
            else ++j,++i;
            if(j==pat_len) {
                cout<<i-pat_len+1<<endl;
            }
        }
        return cnt;
    }
    int Index(char *txt){///返回模式串在主串中首次出现的位置
        int txt_len=strlen(txt),i=0,j=0,cnt=0;
        while(i<txt_len&&j<pat_len){
            if(j!=-1&&txt[i]!=pat[j]) j=nex[j];
            else ++j,++i;
        }
        if(j==pat_len) return i-pat_len;
        else return -1;
    }
}run;
Published 96 original articles · won praise 11 · views 2256

Guess you like

Origin blog.csdn.net/weixin_43769146/article/details/104095593