东方博宜OJ 2337:字符串匹配 ← KMP算法

​【题目来源】
https://oj.czos.cn/p/2337

【题目描述】
给定 2 个仅包含大写字母的字符串 s1,s2,求出 s1 在 s2 中出现的次数。
例如:s1=”ABA”,s2=”ABABA”,输出为:2。输入 T 组数据(T≤20),对每组数据输出结果。
测试数据保证:s1 的长度≤10^4,s2 的长度≤10^6。

【输入格式】
输入的第一行包含一个整数 T,表示测试数据的有多少组。
对于每组数据,先输入一行仅包含大写英文字母的字符串 s1,再输入一行仅包含大写英文字母的字符串 s2。​​​​​​​

【输出格式】
输出有 T 行,每行一个整数,代表每组数据的计算结果。​​​​​​​

【输入样例】
3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN​​​​​​​

【输出样例】
1
3
0

【数据范围】
T≤20,
s1 的长度≤10^4,s2 的长度≤10^6。

【算法分析】
● 本题代码与“东方博宜OJ 2391:子串位置”(https://blog.csdn.net/hnjzsyjyj/article/details/160215718)及其类似,只需微调 KMP 函数代码即可。

【算法代码】

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

const int N=1e6+5;
int ne[N];

void getNext(string t) {
    int len=t.length();
    int i=0,j=-1;
    ne[0]=-1;
    while(i<len) {
        if(j==-1 || t[i]==t[j]) {
            i++,j++;
            ne[i]=j;
        } else j=ne[j];
    }
}

void KMP(string s,string t) {
    int lens=s.length(),lent=t.length();
    int i=0,j=0,cnt=0;
    while(i<lens && j<lent) {
        if(j==-1 || s[i]==t[j]) {
            i++,j++;
        } else j=ne[j];
        if(j==lent) {
            cnt++;
            j=ne[j];
        }
    }
    cout<<cnt<<endl;
}

int main() {
    string s,t;
    int T;
    cin>>T;
    while(T--) {
        cin>>t>>s;
        int len=t.size();
        getNext(t);
        KMP(s,t);
    }
    return 0;
}

/*
in:
3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN

out:
1
3
0
*/



【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/160224665
https://blog.csdn.net/hnjzsyjyj/article/details/160215718
https://blog.csdn.net/hnjzsyjyj/article/details/160228242
 

​

posted @ 2026-04-17 09:15  Triwa  阅读(44)  评论(0)    收藏  举报