zoukankan      html  css  js  c++  java
  • 【HDU2087】KMP

      KMP算法其实很好理解,就是在匹配串中找最近的相同的串。

      下面是HDU的2087:

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<string>
     5 #define maxn 1005
     6 using namespace std;
     7 string s1,s2;
     8 int f[maxn],ans;
     9 void kmp(string &x,string &y)
    10 {
    11     int le=x.size(),j=0,ll=y.size();
    12     for (int i=0;i<le;i++)
    13     {
    14         while (j&&x[i]!=y[j]) 
    15             j=f[j];
    16         if (x[i]==y[j]) j++;
    17         if (j==ll) {
    18             ans++;//j=0;
    19         }
    20     }
    21 }
    22 void find(string &x)
    23 {
    24     int ll=x.size(),j=0;
    25     f[0]=0;f[1]=0;
    26     for (int i=1;i<ll;i++)//从第二个点开始 
    27     {
    28         j=f[j];
    29         while (j&&x[j]!=x[i]) j=f[j];
    30         f[i+1]= x[j]==x[i] ? j+1 : 0;
    31     }
    32 }
    33 int main()
    34 {
    35     //freopen("2087kmp.in","r",stdin);
    36     while (cin>>s1&&s1[0]!='#')//cin不读空格 
    37     {
    38         cin>>s2;
    39         memset(f,0,sizeof (f));
    40         ans=0;
    41         find(s2);
    42         kmp(s1,s2);
    43         cout<<ans<<endl;
    44     }
    45     return 0;
    46 }
    View Code
  • 相关阅读:
    C++官方文档-静态成员
    C++官方文档-this
    C++官方文档-运算符重载
    springboot-dokcer
    HDU 1073
    HDU 1070
    UVa 213
    HDU 1150
    POJ 1274
    POJ 2594
  • 原文地址:https://www.cnblogs.com/lx0319/p/5939957.html
Copyright © 2011-2022 走看看