Visit Counter
AmazingCounters.com

1、题目大意:单字符串匹配问题
2、分析:经典KMP问题
3、代码:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
char P[1000010];
char T[1000010];
int f[1000010];
inline void getfail(){
    int m = strlen(T);
    f[0] = f[1] = 0;
    for(int i = 1; i < m; i ++){
        int j = f[i];
        while(j && T[j] != T[i]) j = f[j];
        if(T[i] == T[j]) f[i + 1] = j + 1;
        else f[i + 1] = 0;
    }
    return;
}
int main(){
    int o;
    scanf("%d", &o);
    while(o --){
        int ans = 0;
        scanf("%s%s", T, P);
        getfail();
        int n = strlen(P), m = strlen(T);
        int j = 0;
        for(int i = 0; i < n; i ++){
            while(j && T[j] != P[i]) j = f[j];
            if(T[j] == P[i]) j ++;
            if(j == m){
                ans ++;
                j = f[j];
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}