題目5: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

算法思想:

可以使用普通的循環遍歷加回溯就可以,因爲目標串最大10000個字符,模式串最大10個字符,故不會超時。當然也可以使用KMP算法。還有更簡單的就是使用C++STL庫中string類的find的函數。

源代碼

/*
Author:楊林峯
Date:2017.10.20
NYOJ(5):Binary String Matching
*/
#include <iostream>
#include <string>
using namespace std;
int getNum(string pattern, string target)
{
    int len1 = pattern.length(), len2 = target.length();
    int i, j, ans = 0;
    for (i = 0; i <= len2 - len1; i++)
    {
        int tmp = i;
        for (j = 0; j < len1;)
        {
            //當模式串與目標串字符相等時,繼續比較下一個字符
            if (pattern[j] == target[i])
            {
                i++;
                j++;
            }
            //否則,跳出循環
            else
            {
                break; 
            }
            //cout << i << " " << j << endl;
        }
        //判斷目標串是否成功
        if (j >= len1)
            ans++;
        //回溯
        i = tmp;
        j = 0;
    }
    return ans;
}
int main()
{
    int N, ans;
    string pattern, target;
    cin >> N;
    while (N--)
    {
        cin >> pattern >> target;
        ans = getNum(pattern, target);
        cout << ans << endl;
    }
    return 0;
}

最優源代碼


#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s1,s2;
    int n;
    cin>>n;
    while(n--)
    {
        cin>>s1>>s2;
        unsigned int m=s2.find(s1,0);
        int num=0;
        while(m!=string::npos)
        {
            num++;
            m=s2.find(s1,m+1);
        }
        cout<<num<<endl;
    }
}        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章