KMP模式匹配算法模板
模板1:
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 void InitNext(char *s, int *next){ 5 int i = 0, j = -1, len = strlen(s); 6 next[0] = -1; 7 while(i < len){ 8 if (j == -1 || s[i] == s[j]){ 9 ++i; 10 ++j; 11 next[i] = j; 12 } 13 else j = next[j]; 14 } 15 } 16 17 int IndexKMP(char T[], char s[], int *next){ 18 int i = 0, j = -1, l = strlen(s), L = strlen(T); 19 InitNext(s, next); 20 while(j < l && i < L){ 21 if (j == -1 || T[i] == s[j]){ 22 ++i; 23 ++j; 24 } 25 else j = next[j]; 26 } 27 if (j >= l) return i-j+1; 28 else return 0; 29 } 30 31 int main() 32 { 33 char T[200], s[20]; 34 int next[20]; 35 scanf("%s %s", T, s); 36 int ans = IndexKMP(T, s, next); 37 cout<<ans<<endl; 38 return 0; 39 }
模板2(大白书):
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn = 1000 + 10; 4 5 void getFail(char* P, int* f) { 6 int len = strlen(P); 7 f[0] = f[1] = 0; 8 for (int i = 1; i < len; ++i) { 9 int j = f[i]; 10 while(j && P[i] != P[j]) j = f[j]; 11 f[i+1] = P[i] == P[j] ? j + 1 : 0; 12 } 13 } 14 15 int find(char* T, char* P, int* f) { 16 int len1 = strlen(T), len2 = strlen(P); 17 getFail(P, f); 18 int j = 0; 19 for (int i = 0; i < len1; ++i) { 20 while(j && T[i] != P[j]) j = f[j]; 21 if (T[i] == P[j]) ++j; 22 if (j == len2) return i - j + 1; 23 } 24 } 25 26 int main() { 27 char T[maxn], P[maxn]; 28 int f[maxn]; 29 while(cin>>T>>P) { 30 cout<<find(T, P, f)<<endl; 31 } 32 33 return 0; 34 }