zoukankan      html  css  js  c++  java
  • KMP算法模板

     1 #include <cstdio>
     2 #include <cstring>
     3 using namespace std;
     4 #define N 10010
     5 #define M 1000010
     6 
     7 char S[M], T[N];
     8 int next[N];
     9 
    10 void Get_next()
    11 {
    12     int i=0, j=-1;
    13     next[0] = -1;
    14     int lt = strlen(T);
    15     while(i<lt)
    16     {
    17         if(j==-1 || T[i]==T[j])
    18             next[++i] = ++j;
    19         else j = next[j];
    20     }
    21 }
    22 
    23 int KMP()
    24 {
    25     int i=0, j=0, cnt=0;
    26     int ls = strlen(S), lt=strlen(T);
    27     Get_next();
    28     while(i<ls && j<lt)
    29     {
    30         if(S[i]==T[j] || j==-1)
    31             i++, j++;
    32         else
    33             j = next[j];
    34         if(j==lt) //得到一个子串
    35         {
    36             cnt++;
    37             j = next[j];
    38         }
    39     }
    40     return cnt;
    41 }
    42 
    43 int main()
    44 {
    45     int n;
    46     while(~scanf("%d", &n))
    47     {
    48         for(int i=0; i<n; i++)
    49         {
    50             scanf("%s%s", T, S);
    51             printf("%d
    ", KMP());
    52         }
    53     }
    54     return 0;
    55 }
  • 相关阅读:
    FR #3题解
    L3-005. 垃圾箱分布
    L2-004. 这是二叉搜索树吗?
    L2-002. 链表去重
    L1-009. N个数求和
    L3-003. 社交集群
    L3-004. 肿瘤诊断
    L2-001. 紧急救援
    L3-002. 堆栈
    L2-007. 家庭房产
  • 原文地址:https://www.cnblogs.com/khan724/p/4156085.html
Copyright © 2011-2022 走看看