1.区别
kmp是用于假设给主串a和模式串b然后求的是b在a中出现的位置,ekmp求的是假设给一个主串a,要求求以a的每个的开头为开始点,然后求它对于原字符串的出现的次数,然后存在extend数组中
2.1思路:
kmp的核心是一个next数组,next[i]用于储存的是当前到i这个位置的时候的最长的公共前后缀的长度,求得这个长度之后,假设当前模式串的j位置与主串不符合,按照传统的思路是需要把主串的开头向前移动一位,重新比较,但是kmp数组可以用next数组来把模式串进行移动,之后在于主串进行比较
模板:(用于子串出现的位置)
#include <stdio.h>
#include<string.h>
#define maxn 1000001
typedef long long ll;
using namespace std;
int next[maxn];
char f[maxn],c[maxn];
void GetNext(char *str)
{
int len=strlen(str);
int i=0,j=-1;
next[0]=-1;
while(i<len)
{
if(j==-1||str[i]==str[j])
{
i++;j++;
next[i]=j;
}
else
{
j=next[j];
}
}
}
ll kmp(char *f,char *c)
{
ll lenf=strlen(f);
ll lenc=strlen(c);
GetNext(c);
ll i=0,j=0;
while(i<lenf&&j<lenc)
{
if(f[i]==c[j]||j==-1)
{
i++,j++;
}
else
{
j=next[j];
}
}
if(j==lenc)
{
return i-j;
}
return -1;
}
int main(int argc, char *argv[])
{
char a[1001];
char b[1001];
while(scanf("%s %s",a,b)!=EOF)
{
printf("%lld\n",kmp(a,b));
}
return 0;
}
统计出现次数模板
int KmpCount()
{
int i=0,j=0;
int k=0;
int l1 = strlen(c1);
int l2 = strlen(c2);
GetNext();
while(i<l2)
{
if(j == -1 || c2[i]==c1[j])
{
i++;
j++;
}
else
j = nex[j];
if(j == l1)
{
k++;
i--,j--;
j=nex[j];
}
}
return k;
}
2.2EKMP思路:
ekmp的关键也是在于next数组,next[i]数组表示的是原字符串以i为开头的于原字符串以0开头的最长公共子序列,求得next之后
开始经行匹配,首先在每次匹配时我们都会存下从之前到当前位置i-1匹配时候的最长的一个子序列的长度记录为extend[po],那么在求i的时候我们可以知道extend[po]+po(假设i+1的点也匹配到了po那个位置,那么从i-po这个位置的长度就为po+extend[po]),然后记得我们上一步已经求得了模式串的next[i-po]+i(表示的是以模式串以0为开头与主串以i为开头的无需匹配的长度),然后有两种情况:第一种next[i-po]+i>=entend[po]+po则需要从主串的entext[po]+po和模式串的extend[po]+po-i为开头继续匹配。第二种情况:next[i-po]+i<entend[po]+po则extend[i]的长度就为next[i-po]
模板:
const int MAX=100010; //字符串长度最大值
int Next[MAX],extend[MAX];
//预处理计算Next数组
void getNext(char str[])
{
int i=0,j,po,len=strlen(str);
next[0]=len; //初始化next[0]
while(str[i]==str[i+1] && i+1<len) i++; next[1]=i; //计算next[1]
po=1; //初始化po的位置
for(i=2;i<len;i++)
{
if(next[i-po]+i < next[po]+po) //第一种情况,可以直接得到next[i]的值
next[i]=next[i-po];
else //第二种情况,要继续匹配才能得到next[i]的值
{
j = next[po]+po-i;
if(j<0) j=0; //如果i>po+next[po],则要从头开始匹配
while(i+j<len && str[j]==str[j+i]) j++; next[i]=j;
po=i; //更新po的位置
}
}
}
//计算extend数组
void EXKMP(char s1[],char s2[])
{
int i=0,j,po,len=strlen(s1),l2=strlen(s2);
getNext(s2); //计算子串的next数组
while(s1[i]==s2[i] && i<l2 && i<len) i++; extend[0]=i;
po=0; //初始化po的位置
for(i=1;i<len;i++)
{
if(next[i-po]+i < extend[po]+po) //第一种情况,直接可以得到extend[i]的值
ex[i]=next[i-po];
else //第二种情况,要继续匹配才能得到extend[i]的值
{
j = extend[po]+po-i;
if(j<0) j=0; //如果i>extend[po]+po则要从头开始匹配
while(i+j<len && j<l2 && s1[j+i]==s2[j]) j++; extend[i]=j;
po=i; //更新po的位置
}
}
}
这篇文章写的比较乱,只是用于个人的总结和理清思路