Binary String Matching


题目描述:

 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.

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

分析感悟:刚看这道题的时候有点无从入手,最后花费了好长时间用了不同的思路写出了解题的代码,最后我还是选择了这个易于理解的解题思路;往往越容易理解的东西越会使人感觉冗杂,而对于程序设计来说,越是容易理解的代码却会占用更大的内存、消耗更长的运行时间(也就是时间复杂度的问题)。在这到程序设计题中,直接用了朴素算法,而朴素算法的关键在于回溯,因此只要了解回溯,处理好回溯问题,那么以后遇到类似思想题的时候,都会迎刃而解。

回溯算法:回溯(backtracking)是一种系统的搜索问题解答的方法。为了实现回溯,首先需要为问题定义一个空间(solution space)这个空间必须是至少包含问题的一个解(可能是最优解)。下一步是组织解空间以便它能被容易地搜索, 一旦定义了解空间的组织方法,这个空间即可按深度优先的方法从开始节点进行搜索。

回溯方法的步骤如下:

    (1) 定义一个解空间,它包含问题的解。
    (2) 用适于搜索的方式组织该空间。
    (3)用深度优先法搜索该空间,利用限界函数避免移动到不可能产生解的子空间。


  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值