• hihocoder 1015题


    代码

     1 #include <iostream>
     2 #include <string>
     3 #include <typeinfo>
     4 #include <vector>
     5 using namespace std;
     6 
     7 int KMP(const string &pattern,const string &str)
     8 {
     9     const int len1 = pattern.length();
    10     const int len2 = str.length();
    11     vector<int> next(len1);
    12     next[0]=0;
    13     int i,j,k;
    14     for (i=1;i<len1;i++)
    15     {
    16         k=next[i-1];
    17         while (pattern[i] != pattern[k]&&k!=0)
    18         {
    19             k=next[k-1];
    20         }
    21         if(pattern[i] == pattern[k])
    22             next[i]=k+1;
    23         else
    24             next[i]=0;
    25     }
    26     i=j=0;
    27     int mycount=0;
    28     while (j < len2)
    29     {
    30         if (pattern[i]!=str[j])
    31         {
    32             if (i==0)
    33             {
    34                 i=0;
    35                 j++;
    36             }
    37             else
    38                 i=next[i-1];
    39         }
    40         else
    41         {
    42             i++;
    43             j++;
    44             if(pattern[i] == '')
    45             {
    46                 mycount++;
    47                 i=next[len1-1];//为什么取pattern最后一个字符的next,自己想
    48                 //i赋值位next[len1-1]是为了防止j回溯
    49             }
    50         }
    51     }
    52 
    53     return mycount;
    54 }
    55 
    56 int main()
    57 {
    58     int n;
    59     string pattern,str;
    60     while (cin >> n)
    61     {
    62         while (n--)
    63         {
    64             cin >> pattern >> str;
    65             cout << KMP(pattern,str)<<endl;
    66         }
    67     }
    68     return 0;
    69 }
  • 相关阅读:
    Java 类和Static关键字
    算法与数据结构实验题 6.4 Summary
    Django-----vue结合上传图片
    Django----模板继承&过滤器
    Django-----多对多示例查询
    Django-----验证码
    Django-----序列化--jwt
    Django-----文件配置
    Django-----删除--批量删除
    Django-----图文混排
  • 原文地址:https://www.cnblogs.com/LCCRNblog/p/5836376.html
Copyright © 2020-2023  润新知