pat表示模式串,txt表示文本串,nex[i]表示pat中0~(i-1)最长相同前后缀。
KMP求pat在txt出现的次数或位置。 模式串的nex数组类似与ac自动机的fail指针,当发生不匹配时,跳到已匹配后缀最长的相同前缀的位置。求nex数组的过程就是pat自我匹配的过程。
学习链接:传送门 注意这个博客的预定约定和本文代码的约定不同
#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];
++j,++i;
if(j==pat_len) ++cnt;
}
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];
++j,++i;
}
if(j==pat_len) return i-pat_len;
else return -1;
}
}run;
int main(){
scanf("%s",run.pat);
run.GetNext();
return 0;
}
来源:CSDN
作者:jjl0229
链接:https://blog.csdn.net/weixin_43769146/article/details/104095593