KMP串匹配算法
Brute Force
KMP
Failure Function
Code
BF
#include <stdio.h>
int n, m;
char a[500000], b[500000];
int Index(char*S, char*T, int pos){
int i=pos-1, j=0;
while(i<n){
if(S[i]==T[j]){
++i; ++j;
if(j==m) return i-m+1;
}else{
i=i-j+1; j=0;
}
}
return 0;
}
int main() {
int pos=0;
scanf("%d", &n); getchar(); gets(a);
scanf("%d", &m); getchar(); gets(b);
scanf("%d", &pos);
printf("%d", Index(a,b,pos));
return 0;
}
KMP
#include <stdio.h>
int n, m;
int cont_str(char *s)
{
int i = 0;
while ( s[i++] != '\0');
return i-1;
}
void get_next(char *T, int *next){
int i = 1;
next[1] = 0;
int j = 0;
while (i<m){
if(j==0 || T[i-1]==T[j-1]){
++i;
++j;
next[i]=j;
}else{
j = next[j];
}
}
}
int KMP(char *S, char *T, int pos){
int next[500000];
int i = pos, j = 1;
get_next(T, next);
while(i<= n && j <= m){
if (j ==0 || S[i-1]==T[j-1]){
++i;++j;
}else{
j = next[j];
}
}
if (j >m) return i-m;
else return 0;
}
int main() {
int pos;
char a[500000],b[500000];
gets(a); gets(a); n = cont_str(a);
gets(b); gets(b); m = cont_str(b);
scanf("%d", &pos);
int index= KMP(a,b,pos);
printf("%d",index);
}
拓展
继续挖坑