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

    参考:http://www.cnblogs.com/c-cloud/p/3224788.html

     1 #include<stdio.h>
     2 #include<string.h>
     3 void makeNext(const char P[],int next[])
     4 {
     5     int q,k;
     6     int m = strlen(P);
     7     next[0] = 0;
     8     for (q = 1,k = 0; q < m; ++q)
     9     {
    10         while(k > 0 && P[q] != P[k])
    11             k = next[k-1];
    12         if (P[q] == P[k])
    13         {
    14             k++;
    15         }
    16         next[q] = k;
    17     }
    18 }
    19 
    20 int kmp(const char T[],const char P[],int next[])
    21 {
    22     int n,m;
    23     int i,q;
    24     n = strlen(T);
    25     m = strlen(P);
    26     makeNext(P,next);
    27     for (i = 0,q = 0; i < n; ++i)
    28     {
    29         while(q > 0 && P[q] != T[i])
    30             q = next[q-1];
    31         if (P[q] == T[i])
    32         {
    33             q++;
    34         }
    35         if (q == m)
    36         {
    37             printf("Pattern occurs with shift:%d
    ",(i-m+1));
    38         }
    39     }    
    40 }
    41 
    42 int main()
    43 {
    44     int i;
    45     int next[20]={0};
    46     char T[] = "ababxbababcadfdsss";
    47     char P[] = "abcdabd";
    48     printf("%s
    ",T);
    49     printf("%s
    ",P );
    50     // makeNext(P,next);
    51     kmp(T,P,next);
    52     for (i = 0; i < strlen(P); ++i)
    53     {
    54         printf("%d ",next[i]);
    55     }
    56     printf("
    ");
    57 
    58     return 0;
    59 }
  • 相关阅读:
    闭包(closure)与协程共用时要注意的事情
    mysql---视图
    职责链模式
    JavaScript DOM(一)
    9.7 迭代
    [BLE--Link Layer]设备蓝牙地址
    Loopback測试软件AX1用户手冊 V3.1
    操作系统
    OpenCV特征点检測------Surf(特征点篇)
    linux 命令 xxd
  • 原文地址:https://www.cnblogs.com/zqy123/p/5993296.html
Copyright © 2011-2022 走看看