题目大意:给出两个字符串,问第一个字符串在第二个字符串中出现了几次

解题思路:KMP的裸题了,如果匹配成功,就用next数组代替,然后继续匹配下去,这题考查的是对next数组的理解

#include <cstdio>
#include <cstring>
const int N = 1000010;
char a[N], b[N];
int next[N];
int lena, lenb;

void getFail() {
    next[0] = -1;
    int i = 0, j = -1;
    while (i < lena) {
        if (j == -1 || a[i] == a[j]) {
            i++; j++;
            next[i] = j;
        }
        else j = next[j];
    }
}

void init() {
    scanf("%s%s", a, b);
    lena = strlen(a);
    lenb = strlen(b);
    getFail();
}

void solve() {
    int i = 0, j = 0, ans = 0;
    while (i < lenb) {
        if (j == -1 || a[j] == b[i]) {
            i++; j++;
            if (j == lena) {
                ans++;
                j = next[j];
            }
        }
        else j = next[j];
    }
    printf("%d\n", ans);

}

int main() {
    int test;
    scanf("%d", &test);
    while (test--) {
        init();
        solve();
    }
    return 0;
}