「POJ 3461」Oulipo - KMP

给出两个字符串,求一个字符串在另一个字符串中的出现次数。

题解

KMP 裸题,拿来练练模板 ……

注意 next 千万不要声明成 char 型,别问我为什么要说这个 ……

代码

#include <cstdio>
#include <cstring>

const int MAXN = 10000;
const int MAXM = 1000000;

int m, n, next[MAXN + 1];
char s[MAXM + 1], p[MAXN + 1];

inline void getNext() {
    next[0] = -1;
    for (int i = 0, j = -1; i < n; ) {
        if (j == -1 || p[i] == p[j]) next[++i] = ++j;
        else j = next[j];
    }
}

inline int kmp() {
    getNext();
    int ans = 0;
    for (int i = 0, j = 0; i < m; ) {
        if (j == -1 || s[i] == p[j]) i++, j++;
        else j = next[j];
        if (j == n) ans++, j = next[j];
    }
    return ans;
}

int main() {
    int t;
    scanf("%d", &t), getchar();
    while (t--) {
        gets(p);
        gets(s);
        n = strlen(p);
        m = strlen(s);
        // n = readLine(p);
        // m = readLine(s);
        printf("%d\n", kmp());
    }
    return 0;
}