奥赛一本通 1455 Oulipo

1455 Oulipo

题目大意

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

知识要点

KMP

解题思路

直接利用 KMP 算法匹配即可。

参考代码

#include <bits/stdc++.h>
using namespace std;

char s[10005], t[1000005];
int T, f[10005];
int main() {
    scanf("%d", &T);
    while(T--) {
        scanf("%s%s", s, t);
        int ans = 0, m = strlen(s), n = strlen(t);
        for(int i = 1, j = 0; i < m; i++) {
            while(j && s[i] != s[j]) j = f[j - 1];
            if(s[i] == s[j]) j++;
            f[i] = j;
        }

        for(int i = 0, j = 0; i < n; i++) {
            while(j && t[i] != s[j]) j = f[j - 1];
            if(t[i] == s[j]) j++;
            if(j == m) ans++, j = f[j - 1];
        }
        printf("%d\n", ans);
    }
    return 0;
}
posted @ 2026-09-20 14:51  萧西待水  阅读(22)  评论(0)    收藏  举报