Binary String matching time limit: theMs | Memory Limit:65535KB Difficulty:3
-
-
Describe
-
Given 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 ' and the pattern string A is ' one ', you should output 3, because the patter N A appeared at the posit
-
Input
-
The first line consist only one integer n, indicates n cases follows. In each case, there is lines, the first line gives the string A, Length (a) <=, and the second line gives the S Tring B, Length (b) <= 1000. And it is guaranteed this B is always longer than A.
-
Output
-
For each case, the output a single line consist a single integer, tells how the many times do B appears as a substring of a.
-
Sample input
-
-
Sample output
-
Test instructions: Find out the number of occurrences of the pattern string in the main string.
Naive algorithm Code:
#include <cstdio> #include <cstring>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", b); Len=strlen (b); while (I<=len) { if (a[j]== ') } { count++; i=i-j+1; j=0; } else if (A[j]==b[i]) { i++; j + +; } else { i=i-j+1;//The key is backtracking j=0; } } printf ("%d\n", count); } return 0;}
KMP algorithm:
#include <cstdio> #include <cstring>int nextval[200];void get_next (char a[])//Get next array; { int len; int i=0,j=-1; Nextval[0]=-1; Len=strlen (a); while (I<=len) { if (J==-1 | | a[i]==a[j]) { ++i; ++j; if (A[i]==a[j]) nextval[i] = nextval[j]; Replace the backtracking content with the next array; else nextval[i] = j; } else j=nextval[j];} } int KMP (char a[],char b[])//kmp the body function { int i=0,j=0,count=0; int Lena,lenb; Lena=strlen (a); Lenb=strlen (b); Get_next (a); while (I<=lenb) { if (J==-1 | | a[j]==b[i]) { ++i; ++j; } else J=nextval[j]; if (J>=lena) { count++; J=NEXTVAL[J]; } } return count;} int main () { int n; Char a[20],b[1200]; scanf ("%d", &n); while (n--) { scanf ("%s\n%s", A, b); printf ("%d\n", KMP (A, b)); } return 0;}
Nyoj5 Binary String Matching (KMP)