【题目来源】
https://oj.czos.cn/p/1477
【题目描述】
一个字符串中任意个连续的字符组成的子序列为该字符串的子串。给定子串 s1 和它的一个字符串 s2,求 s1 在 s2 中出现的次数。
【输入格式】
第一行,表示字符串 s1,第二行表示字符串 s2。
【输出格式】
一个整数,代表 s1 在 s2 中出现的次数。
【输入样例】
ab
abbaabcaabc
【输出样例】
3
【数据范围】
/
【算法分析】
● BF 算法:https://blog.csdn.net/hnjzsyjyj/article/details/127044421
● 本题是个"入门"级题目,数据规模不大,不会达到 BF 算法"发病"的地步。
【算法代码】
cpp
#include <bits/stdc++.h>
using namespace std;
int BF(string S,string T) {
int cnt=0,i=0,j=0;
while(i<S.length() && j<T.length()) {
if(S[i]==T[j]) i++,j++;
else i=i-j+1,j=0;
if(j==T.length()) cnt++,j=0;
}
return cnt;
}
int main() {
string s,t;
getline(cin,t);
getline(cin,s);
cout<<BF(s,t);
return 0;
}
/*
in:
ab
abbaabcaabc
out:
3
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/127044421