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)用深度優先法搜尋該空間,利用限界函式避免移動到不可能產生解的子空間。