ZOJ 3957 Knuth-Morris-Pratt Algorithm

本文介绍了一种利用KMP算法解决字符串匹配问题的方法,并通过一个具体例子——寻找字符串中“cat”和“dog”的出现次数——来展示如何实现这一算法。文章提供了完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值