NYOJ 5 Binary String Matching

#include<stdio.h>
#include<string.h>
int main()
{
  int num,count;
  scanf("%d\n",&num);
  //getchar();
  while(num--)
  {
    count=0;
    int i=0,j=0,len;
    char a[200],b[1200];
    scanf("%s\n%s",a,b);
    len=strlen(b);
    while(i<=len)
    {
      if(a[j]=='\0')
      {
        count++;//出现一次加一次
        i=i-j+1; i回溯
        j=0;
      }
      else if(a[j]==b[i])
      {
        i++;
        j++;
      }
      else
      {
        i=i-j+1; i回溯
        j=0;
      }
      //printf("%d\n",count);
    }
    printf("%d\n",count);
  }
}

//KP算法  刚开始看这题时,没有理解正确,以为只是简单地kp问题,其实题目让求的是,a串在b串出现的次数 

/*

以下是最优代码,,

#include<iostream>
#include<string.h>
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;
  }
}*/

posted @ 2015-07-04 15:49  小松鼠。  阅读(117)  评论(0编辑  收藏  举报