NYACM_005

NYACM_005

题目:Binary String Matching
链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=5
描述:

描述
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.
样例输入
3
11
1001110110
101
110010010010001
1010
110100010101011
样例输出
3
0
3

分析:

寻找子串个数,之前有看到过相关文章,貌似最快的是sunday 算法,其实如果不考虑练习算法,单纯求解的话,貌似最简单的是利用string的查找子串find()函数,如果没找到直接是0,找到了,从开始到找到位置截掉,剩下部分再次查找,直到不存在子串,即可得到次数。

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int NYACM_005()
{
    int N;
    cin >> N;
    while (N--)
    {
        string strA;
        string strB;
        int answer = 0;
        cin >> strA >> strB;
        while(strB.find(strA) < 10000)
        {
            answer++;
            strB = strB.substr(strB.find(strA) + 1, strB.size() - strB.find(strA));
        }
        cout << answer << endl;
    }
    return 0;
}

int main()
{   
    NYACM_005();
    return 0;
}

不过字符匹配算法不仅仅可以用作字符匹配上,在其他的任务中也有参考意义,比如之前编程对比文本文档时候就是通过对每一行压缩将一页降维成一行,参考Sunday算法进行对比,其实感觉这一题更多的是考察队字符串匹配算法的掌握。常用的字符串匹配算法可以参考http://www.360doc.com/content/14/0325/15/15064667_363609292.shtml

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值