• nyoj 5 Binary String Matching(kmp)


    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.
    样例输入
    3
    11
    1001110110
    101
    110010010010001
    1010
    110100010101011 
    样例输出
    3
    0
    3 

     1 #include<cstdio>
     2 #include<cstring>
     3 using namespace std;
     4 
     5 int next[105];
     6 
     7 void getnext(char *s)
     8 {
     9     int len=strlen(s);
    10     int i=0,j=-1;
    11     next[i]=j;
    12     while(i<len)
    13     {
    14         if(j==-1||s[i]==s[j])
    15         {
    16             i++;
    17             j++;
    18             next[i]=j;
    19         }
    20         else
    21             j=next[j];
    22     }
    23 }
    24 
    25 int kmp(char *s1,char *s2)
    26 {
    27     int res=0;
    28     int len1=strlen(s1);
    29     int len2=strlen(s2);
    30     getnext(s2);
    31     int i=0,j=0;
    32     while(i<len1)
    33     {
    34         if(j==-1||s1[i]==s2[j])
    35         {
    36             i++;
    37             j++;
    38             if(j==len2)
    39                 res++;
    40         }
    41         else
    42             j=next[j];
    43     }
    44     return res;
    45 }
    46 
    47 int main()
    48 {
    49     int T;
    50     char sub[15],s[1005];
    51     scanf("%d",&T);
    52     while(T--)
    53     {
    54         scanf("%s",sub);
    55         scanf("%s",s);
    56         getnext(sub);
    57         int ans=kmp(s,sub);
    58         printf("%d
    ",ans);
    59     }
    60     return 0;
    61 }
  • 相关阅读:
    MySQL "show users"
    MySQL
    A MySQL 'create table' syntax example
    MySQL backup
    MySQL show status
    Tomcat, pathinfo, and servlets
    Servlet forward example
    Servlet redirect example
    Java servlet example
    How to forward from one JSP to another JSP
  • 原文地址:https://www.cnblogs.com/homura/p/4915168.html
Copyright © 2020-2023  润新知