#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1000005;
const int maxm = 10005;
struct K_M_P{
int target[maxn];
int pattern[maxm];
int next[maxm];
int target_len;
int pattren_len;
};
K_M_P kmp;
int KMP(){
//预处理计算next数组;
kmp.next[0] = 0;
kmp.next[1] = 0;
for(int i = 1; i < kmp.pattren_len; ++i) //递推边界初值
{
int j = kmp.next[i];
while(j && kmp.pattern[i] != kmp.pattern[j]) j = kmp.next[j];
kmp.next[i+1] = kmp.pattern[i] == kmp.pattern[j] ? j + 1 : 0;
}
//kmp
int j = 0; //当前节点编号
for(int i = 0; i < kmp.target_len; ++i) //文本串指针
{
while(j && kmp.pattern[j] != kmp.target[i]) j = kmp.next[j]; //若失配则加next[j] 向下滑行
if(kmp.pattern[j] == kmp.target[i]) j++;
if(j == kmp.pattren_len) //匹配成功
{
printf("%d\n", i - kmp.pattren_len + 1 + 1); //若从零开始计数则+1+1;
return -1;
}
}
return 1; //无匹配
}
KMP算法模板(字符串匹配问题)
最新推荐文章于 2022-03-26 21:45:30 发布