KMP算法我先做一个简单介绍:
朴素算法的时间复杂度N平方,而KMP是N+M。
空间复杂度都为N。
也就是这么多吧,让我们一起来看看代码:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
#define next Next
#define REP(i, a, b) for(i = (a);i <= (b); ++i)
const int maxn = 1000010;
int next[maxn];
char p[maxn], t[maxn], s[maxn];
int ans = 0;
void init(char s2[], char s1[]) {
int len1 = strlen(s1);
int len2 = strlen(s2);
int i = 0, j = -1;
next[0] = -1;
while(i != len2)
if(j == -1 || s1[i] == s1[j])
next[++i] = ++j;
else
j = next[j];
}
void KMP(char s2[], char s1[]) {
int len1 = strlen(s1);
int len2 = strlen(s2);
init(s1, s2);
int i = 0;
int j = 0;
while(i != len1 && j != len2) {
if(s1[i] == s2[j] || j == -1) {
++i;
++j;
}
else
j = next[j];
if(j == len2) {
++ans;
j = next[j];
}
}
}
int main() {
int m, n, i, j, k;
int r, l;
scanf("%s%s", &p, &t);
int plen = strlen(p);
int tlen = strlen(t);
REP(i, 0, tlen - 1) {
l = i, r = i;
while(l >= 0 && r < tlen && t[l] == t[r]) {
REP(j, l, r)
s[j - l] = t[j];
s[r - l + 1] = '\0';
KMP(s, p);
l--,r++;
}
l = i, r = i + 1;
while(l >= 0 && r < tlen && t[l] == t[r]) {
REP(j, l, r)
s[j - l] = t[j];
s[r - l + 1] = '\0';
KMP(s, p);
l--,r++;
}
}
printf("%d\n", ans);
return 0;
}
太容易了,就不做具体介绍了。