1. 程式人生 > >NYOJ 5題------Binary String Matching

NYOJ 5題------Binary String Matching

Binary String Matching

時間限制:3000 ms  |  記憶體限制:65535 KB

難度:3

描述

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 

來源

網路

上傳者

naonao

題目連結:http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=5

題目大意就是陣列A和B,A在B中出現幾次;

題目詳細翻譯可自行百度

#include <stdio.h>
#include <string.h>
int main()
{
    char a[20],b[1010];
    int n,x,y,q,s,t,p;
    scanf("%d",&n);
    for(int o=0;o<n;o++)
    {

        scanf("%s%s",a,b);
        getchar(); //消除回車
        p=0;    
        s=strlen(a);    
        t=strlen(b);    //檢測a,b兩個字串的長度
        for(int i=0;i<t;i++)    //從b[0]開始迴圈
        {
            x=i;                //把i的值賦給x 防止下面++導致上面迴圈出錯
            q=0;                
            for(int j=0;j<s;j++)  //例如: 11           11           11           11        ......  如此上下比較
            {                     //      1001110110  1001110110  1001110110  1001110110      
                y=j;                
                if(b[x]==a[y])      
                    q++;        
                x++;                //x++ 使a、b上下對照
            }                       //這裡迴圈令字串a中的元素分別與b中的s個連續元素比較如果有相等就q++
            if(q==s)                //如果q==t那麼說明上面和下面比較每次都相同 也就是說a在b中出現一次 於是p++
                p++;
        }
        printf("%d\n",p);        
    }
    return 0;
}