题解:P11705 「KTSC 2020 R1」字符串查找

· · 题解

思路:

这是一道经典的字符串同构匹配题,要判断文本串的子串是否和模式串“ 实际上相同 ”,也就是说两串满足字符出现模式完全一致(存在字符双射可以互相转换)。我们用分字符前缀哈希 + 排序对比多重集合的方法就能高效解决:

方法:

我们可以预处理出两个串的分字符哈希值,对每个小写字母单独做一遍前缀哈希,只记录该字母在对应位置是否出现,相当于给每个字母的出现位置打了哈希指纹。 思路整理后就可以写代码了。

Code

#include <bits/stdc++.h>

int findP(char T[], char P[], int N, int M);

using namespace std;
typedef long long ll;
const int MAXN = 1000005;
const ll mod = 998244353;
const ll base = 131;

ll ha1[26][MAXN], ha2[26][MAXN];
ll powb[MAXN];

ll getHash(ll ha[], int l, int len) {
    return (ha[l + len - 1] - ha[l - 1] * powb[len] % mod + mod) % mod;
}

int findP(char T[], char P[], int N, int M) {
    powb[0] = 1;
    for(int i = 1; i <= max(N, M); i++)
        powb[i] = powb[i-1] * base % mod;
    for(int c = 0; c < 26; c++)
        for(int j = 1; j <= N; j++)
            ha1[c][j] = (ha1[c][j-1] * base % mod + (T[j-1] == 'a' + c)) % mod;
    for(int c = 0; c < 26; c++)
        for(int j = 1; j <= M; j++)
            ha2[c][j] = (ha2[c][j-1] * base % mod + (P[j-1] == 'a' + c)) % mod;
    vector<ll> pat(26);
    for(int c = 0; c < 26; c++)
        pat[c] = getHash(ha2[c], 1, M);
    sort(pat.begin(), pat.end());

    int ans = 0;
    vector<ll> cur(26);
    for(int i = 1; i <= N - M + 1; i++) {
        for(int c = 0; c < 26; c++)
            cur[c] = getHash(ha1[c], i, M);
        sort(cur.begin(), cur.end());
        if(cur == pat) ans++;
    }
    return ans;
}