zoukankan      html  css  js  c++  java
  • KMP超强模板贴一份

    while(scanf("%s",str+1)==1 ) {
            int n=strlen(str+1);
            next[1]=0int j=0;
            for(int i=2;i<=n;i++) {
                while(j&&str[j+1]!=str[i]) j=next[j];
                if(str[i]==str[j+1]) j++;
                next[i]=j;
            }
            for(int i=1;i<=n;i++) printf("%d ",next[i]);

     随便给出一个字符串  对应的next数组为

     A B R A C D A B R A

     0 0 0 1 0 1 0 2 3 4

     其实就是找前缀了拉

     模式匹配代码贴一份。

     1 #include <cstdio>
     2 #include <cstring>
     3 #include <algorithm>
     4 #include <cmath>
     5 #include <vector>
     6 #include <list>
     7 #include <queue>
     8 using namespace std;
     9 const int MAX = 1e6+10;
    10 const int inf = 0x3f3f3f3f;
    11 char str1[MAX],str2[MAX];
    12 int next[MAX];
    13 int main()
    14 {
    15     //freopen("in","r",stdin);
    16     //freopen("out","w",stdout);
    17     int cas;
    18     scanf("%d",&cas);
    19     while(cas--) {
    20         scanf("%s %s",str1+1,str2+1);
    21         int n=strlen(str1+1);
    22         next[1]=0int j=0;
    23         for(int i=2;i<=n;i++) {
    24             if(j&&str1[i]!=str1[j+1]) j=next[j];
    25             if(str1[i]==str1[j+1]) j++;
    26             next[i]=j;
    27         }
    28         int ans=0;
    29         int len=strlen(str2+1); j=0;
    30         for(int i=1;i<=len;i++) {
    31             while(j&&str2[i]!=str1[j+1]) j=next[j];
    32             if(str2[i]==str1[j+1]) j++;
    33             if(j==n) ans++;
    34 
    35         }
    36         printf("%d ",ans);
    37 
    38     }
    39 
    40     return 0;
    41 }
  • 相关阅读:
    如何防止源码被盗
    C# WebBrowser 获得选中部分的html源码
    特殊字符和空格
    MySQL性能优化
    mysql5.7新特性探究
    【九】MongoDB管理之安全性
    【八】MongoDB管理之分片集群实践
    【七】MongoDB管理之分片集群介绍
    【六】MongoDB管理之副本集
    【五】MongoDB管理之生产环境说明
  • 原文地址:https://www.cnblogs.com/acvc/p/3732873.html
Copyright © 2011-2022 走看看