In computer science, the Knuth-Morris-Pratt string searching algorithm (or KMP algorithm) searches for occurrences of a “word” W within a main “text string” S by employing the observation that when a mismatch occurs, the word itself embodies sufficient information to determine where the next match could begin, thus bypassing re-examination of previously matched characters.
Edward is a fan of mathematics. He just learnt the Knuth-Morris-Pratt algorithm and decides to give the following problem a try:
Find the total number of occurrence of the strings “cat” and “dog” in a given string s.
As Edward is not familiar with the KMP algorithm, he turns to you for help. Can you help Edward to solve this problem?
问串 S 中有多少子串为 cat
或 dog
?
解题思路
使用 STL 直接判断即可。
代码
#include<bits/stdc++.h>
using namespace std;
string s, t;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int cnt =0 ;
cin>>s;
for(int i=0;i<s.size() - 2;i++)
{
t = s.substr(i, 3);
if(t == "dog" || t== "cat")
cnt++;
}
printf("%d\n", cnt);
}
}