Binary String Matching - string的相关操作


描述
Given two strings A and B, whose alphabet consist only ‘0’ and ‘1’. Your task is only to tell how many times does A appear as a substring of B? For example, the text string B is ‘1001110110’ while the pattern string A is ‘11’, you should output 3, because the pattern A appeared at the posit
输入
The first line consist only one integer N, indicates N cases follows. In each case, there are two lines, the first line gives the string A, length (A) <= 10, and the second line gives the string B, length (B) <= 1000. And it is guaranteed that B is always longer than A.
输出
For each case, output a single line consist a single integer, tells how many times do B appears as a substring of A.

题目大意:
给定两个字符串A和B,其字母表仅包含'0'和'1'。
输出 A出现在B的次数

题目链接:http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=5

总结:
如果可以在B中找到与A 则删除该位置及该位置之前的元素,在进行查找 直到在B中找不到A 即可输出

考察到的知识点:
1.给字符串的赋值方式
2.find() 的返回值(如果查不到则返回string::npos这个函数)
3.erase()的使用


代码:

#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main(int argc,char argv[])
{
    int n;
    scanf("%d",&n);  //有几个样例
    while(n--)       //进行样例的输入
    {
        string s1,s2;
        int num=0;
        char ss1[15],ss2[1005];
        /*
            scanf的输入速度比cin快得多
            scanf 是C语言的函数 不支持string对象
        */
        scanf("%s",ss1);  //输入字串
        s1=ss1;            //把整个字符数组赋值给string对象

        scanf("%s",ss2);   //输入母串
        s2=ss2;             //把整个字符数组赋值给string对象
        /*
            在母串中  如果可以查到    则返回第一次字串在母串中的位置
                      如果不可以查到  则返回sstring::npos
        */
        while(s2.find(s1) != string::npos)//如果在母串中可以查到
        {
            num++;                          //使得出现次数+1
            if(s2.find(s1))                 //如果该位置不是0
                s2.erase(0,s2.find(s1)+1);  //则将该位置及之前的删除
            else  s2.erase(0,1);            //如果该位置是0 则删除该元素
        }
        printf("%d\n",num);                 //输入次数
    }
    return 0;
}

示例:
样例输入

    3
    11
    1001110110
    101
    110010010010001
    1010
    110100010101011 

样例输出

    3
    0
    3 

运行结果

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值