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 

運行結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章