Binary String Matching
2015-04-07 00:23
267 查看
题目描述:
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)用深度优先法搜索该空间,利用限界函数避免移动到不可能产生解的子空间。
相关文章推荐
- Binary String Matching
- 5 Binary String Matching
- Binary String Matching
- Binary String Matching
- 南阳--Binary String Matching
- nyoj-5 Binary String Matching
- NYOJ 5 Binary String Matching
- NYOJ - Binary String Matching
- Binary String Matching
- NYOJ5之Binary String Matching
- NYOJ 5 Binary String Matching
- 5-Binary String Matching
- NYOJ 5 Binary String Matching
- nyoj-5-Binary String Matching
- nyoj-5-Binary String Matching
- Binary String Matching
- NYOJ5——Binary String Matching
- Binary String Matching——个人c++解
- nyoj 3 Binary String Matching
- Binary String Matching