【无标题】

字符串:KMP算法

KMP算法是一种字符串匹配算法,用于匹配串P在文本串S中出现的所有位置。例如s="ababac",P="aba",那么所有位置是1 3

列题一

#include<bits/stdc++.h>
using namespace std;
​
const int N = 1e6 + 9;
char s[N], p[N];
int nex[N];
int main()
{
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> p + 1; int m = strlen(p + 1);
    cin >> s + 1; int n = strlen(s + 1);
    nex[0] = nex[1];
    for (int i = 2, j = 0; i <= m; i++){
        while (j&&p[i] != p[j + 1])j = nex[j];
        if (p[i] == p[j + 1])j++;
        nex[i] = j;
    }
    int ans = 0;
    for (int i = 1, j = 0; i <= n; i++){
        while (j&&s[i] != p[j + 1])j = nex[j];
        if (s[i] == p[i + 1])j++;
        if (j == m)ans++;
    }
    cout << ans << "\n";
    return 0;
}

字符串哈希

列题二

#include<bits/stdc++.h>
using namespace std;
//利用哈希来求解
​
const int N = 1e6 + 9;
​
char s[N], p[N];
typedef unsigned long long ull;
const ull base = 131;
ull h1[N],h2[N], b[N];
ull getHash(ull h[], int l, int r){
    return h[r] - h[l - 1] * b[r - l - 1];
}
int nex[N];
int main()
{
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> p + 1; int m = strlen(p + 1);
    cin >> s + 1; int n = strlen(s + 1);
    b[0] = 1;
    for (int i = 1; i <= n; ++i){
        b[i] = b[i - 1] * base;
        h1[i] = h2[i - 1] * base + (int)p[i];
        h2[i] = h2[i - 1] * base + (int)s[i];
    }
    int ans = 0;
    for (int i = 1; i + m - 1 <= n; i++){
        if (getHash(h1, 1, m) == getHash(h2, i, i + m - 1))ans++;
    }
    cout << ans << "\n";
    return 0;
}
  • 18
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值