比较好的KMP博客

从头到尾彻底理解KMP

模板

#include<map>  
#include<set>  
#include<cmath>  
#include<stack>  
#include<queue>  
#include<cstdio>  
#include<string>  
#include<vector>  
#include<cstring>  
#include<iostream>  
#include<algorithm>  
#include<functional>  
using namespace std;  
  
const int MX = 1e6 + 5;  
  
char S1[MX], S2[MX];  
int Next[MX];  
  
int KMP(char *A, char *B) {  
    int m = strlen(A), n = strlen(B);  
  
    Next[0] = 0;  
    for(int i = 1; i < n; i++) {  
        int k = Next[i - 1];  
        while(B[i] != B[k] && k) k = Next[k - 1];  
        Next[i] = B[i] == B[k] ? k + 1 : 0;  
    }  
  
    int ans = 0, j = 0;  
    for(int i = 0; i < m; i++) {  
        while(A[i] != B[j] && j) j = Next[j - 1];  
        if(A[i] == B[j]) j++;  
        if(j == n) ans++;  
    }  
    return ans;  
}  
  
int main() {  
    int T, ansk = 0;  
    //freopen("input.txt", "r", stdin);  
    scanf("%d", &T);  
    while(T--) {  
        scanf("%s%s", S1, S2);  
        printf("%d\n", KMP(S2, S1));  
    }  
    return 0;  
} 

 

posted @ 2018-04-27 10:53  摇啊摇啊  阅读(132)  评论(0编辑  收藏  举报