【斤斤计较的小Z——KMP / hash】

题目

KMP代码

#include <bits/stdc++.h>
using namespace std;

const int N = 1e6+10;

char s[N], p[N];
int nex[N];

int main()
{
  cin >> p+1 >> s+1;
  int n = strlen(s+1);
  int m = strlen(p+1);
  
    //思路也是一致的,只要in > 0,就尝试拯救,最后补充一次匹配,如果不行就是0,如果行就是其它
    for(int i = 2, j = 0; i <= m; i++)
    {
        while(j && p[j+1] != p[i]) j = nex[j];
        if(p[j+1] == p[i]) j++; //要么nex成功,要么j=0(此时也有可能匹配)
        nex[i] = j;
    }

    int cnt = 0;
    for(int i = 1, j = 0; i <= n; i++)
    {
        while(j && p[j+1] != s[i]) j = nex[j];
        if(p[j+1] == s[i]) j++;
        if(j == m)
        {
          j = 0;
          cnt++;
        }
    }

    cout << cnt;
}

hash代码

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

const int N = 1e6+10;
char s1[N], s2[N];

const int base = 233;
const int mod = 1e9+7;

ll f[N], qp[N];

ll get_hash(int l, int r)
{
  ll ret = (f[r] - f[l-1] * qp[r-l+1] % mod + mod) % mod;

  return ret;
}
int main()
{
  cin >> s1+1 >> s2+1;
  int m = strlen(s1+1);
  int n = strlen(s2+1);

  qp[0] = 1;
  for(int i = 1; i <= n; i++)
  {
    qp[i] = qp[i-1] * base % mod;
    f[i] = f[i-1] * base % mod + s2[i];
    f[i] %= mod;
  }

  ll hash1 = 0;
  for(int i = 1; i <= m; i++)
  {
    hash1 = hash1 * base % mod + s1[i];
    hash1 %= mod;
  }

  int cnt = 0;
  for(int i = 1; i + m - 1 <= n; i++)
  {
    int l = i, r = i+m-1;
    if(get_hash(l, r) == hash1) cnt++;
  }

  cout << cnt;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值