『题解』Luogu P8195 A. 小智的疑惑
题目大意
给定一个只包含小写字母的字符串 \(s\),求 \(s\) 中出现了多少次子串 chuanzhi。
思路
STL yyds。
直接用 string 中的 find()。
需要一个 while 循环,条件为 \(s\) 中存在子串 chuanzhi。
每次循环将找到的第一个 chuanzhi 并跳过,并累加答案。
\(s\) 中没有子串 chuanzhi 后即可输出答案。
代码
#include <iostream>
using namespace std;
int idx,ans; // idx 表示现在跳到哪里了
string s;
int main(){
cin >> s;
while(s.find("chuanzhi",idx)!=string::npos){
idx=s.find("chuanzhi",idx)+1;
ans++;
}
cout << ans << endl;
return 0;
}

浙公网安备 33010602011771号