ZOJ 3957 Knuth-Morris-Pratt Algorithm

来源:互联网 发布:跟淘宝合作的购物软件 编辑:程序博客网 时间:2024/06/12 21:27

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 中有多少子串为 catdog

解题思路

使用 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);    }}
0 0
原创粉丝点击