模板类(KMP)

模板KMP

#include <bits/stdc++.h>
using namespace std; 
const int mod = 998244353;
const int N = 200005;
const int inf = 0x3f3f3f;
typedef long long ll;
using pii = pair<int, int>;

vector<int>pre(string s) // 求子串模式串(前缀函数)
{
    int n = s.size();
    vector<int> f(n + 1);
    for (int i = 1, j = 0; i < n; i++)
    {
        while (j && s[i] != s[j])
        {
            j = f[j];
        }
        j += (s[i] == s[j]);
        f[i + 1] = j;
    }
    return f;
}

vector<int>kmp(string a, string b)//记录出现的所有匹配的下标(0-index)
{
    if (b.empty()) 
    {
        // 空模式串匹配所有位置
        vector<int> all_pos(a.size());
        iota(all_pos.begin(), all_pos.end(), 0);
        return all_pos;
    }
    vector<int> f = pre(b);
    vector<int> oc;
    int n = a.size();
    int m = b.size();
    int j = 0;
    for (int i = 0; i < n; i++)
    {
        while (j && a[i] != b[j])
        {
            j = f[j];
        }
        if (a[i] == b[j])
        {
            j++;
        }
        if (j == m)
        {
            oc.push_back(i - m + 1);
            j = f[j];
        }
    }
    return oc;
}

void graspppp()
{
    string a, b;
    cin >> a >> b;
    auto ans = kmp(a,b);
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int T = 1;
    // cin>>T;
    while (T--)
        graspppp();
    return 0;
}
posted @ 2025-06-05 09:33  graspppp  阅读(7)  评论(0)    收藏  举报