跳到正文

个人记录

8.20-8.22【字符串】字符串哈希

Void_Rift约 23 分钟
原文

这是 2026年8月24日 存档的第 2 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年8月22日
收录
2026年8月23日
更新
2026年11月15日
篇幅
约 23 分钟

版本

  1. v3当前
  2. v2
  3. v1

字符串哈希\text{字符串哈希}

【字符串】字符串哈希

课堂练习

-P8835 [传智杯 #3 决赛] 子串-

思路

  • 纯暴力

Code

C++
#include<bits/stdc++.h>
#define int long long
#define pii pair<int,int>
using namespace std;
const int N=1e6+10,maxl=1e3+10,inf=0x3f3f3f3f3f3f,mod=1e9+7,LOG=60;
int T,n,m;
string s,t;
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>T;
    while(T--)
    {
        int ans=0;
        cin>>n>>m;
        cin>>s>>t;
        //全部转小写
        for(int i=0;i<s.size();i++)
        {
            if(s[i]>='A' && s[i]<='Z') s[i]=(char)s[i]+32;
        }
        for(int i=0;i<t.size();i++)
        {
            if(t[i]>='A' && t[i]<='Z') t[i]=(char)t[i]+32;
        }
        for(int i=0;i<m;i++)
        {
            if(t[i]==s[0])
            {
                string x=t.substr(i,s.size());
                //字符串.substr(初始位置,需截取长度)
                if(x==s) ans++;//统计答案
            }
        }
        cout<<ans<<"\n";
    }
    return 0;
}

-P10468 兔子与兔子-

思路

  • 字符串哈希之子串哈希模板
数组定义
  • hsi:hs_i: 表示字符串前 ii 个字符组成的前缀的哈希值
  • pwi:pw_i: 基底 pp 的 ii 次方,用于子串哈希的位数对齐

  • 题目需要判断两个子串是否一样,那么就需要计算字符串中区间 [l,r][l,r] 的子串的哈希值
  • 计算公式:
hash(l,r)=hsr−hsl−1×pwr−l+1hash(l,r)=hs_r-hs_{l-1}\times pw_{r-l+1}
  • 原理:前缀哈希是从左到右按高位计算的,hsl−1hs_{l-1} 对应的是前 l−1l-1 位的哈希值,乘以 pwr−l+1pw_{r-l+1} 相当于把它左移到和 hsrhs_r 相同的高位,再相减就得到了中间子串独立的哈希值
  • 有了哈希值,我们现在就只需要判断两个子串的哈希值是否相等即可

Code

C++
#include<bits/stdc++.h>
#define int unsigned long long
#define pii pair<int,int>
using namespace std;
const int N=1e6+10,maxl=1e3+10,inf=0x3f3f3f3f3f3f,mod=1e9+7;
const int p=131;
int n;
int hs[N],pw[N];
string s;
int get_hash(int l,int r)
{
    return hs[r]-hs[l-1]*pw[r-l+1];
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>s>>n;
    int len=s.size();
    s='@'+s;
    pw[0]=1;
    for(int i=1;i<=len;i++)
    {
        hs[i]=hs[i-1]*p+s[i];
        pw[i]=pw[i-1]*p;
    }
    while(n--)
    {
        int l1,r1,l2,r2;
        cin>>l1>>r1>>l2>>r2;
        int tmp1=get_hash(l1,r1),tmp2=get_hash(l2,r2);
        cout<<((tmp1==tmp2)? "Yes":"No")<<"\n";
    }
    return 0;
}

-CF39J Spelling Check-

Codeforces
DreamOj

思路

  • 另一个子串哈希模板
数组定义
  • hsi:hs_i: 表示字符串前 ii 个字符组成的前缀的哈希值
  • pwi:pw_i: 基底 pp 的 ii 次方,用于子串哈希的位数对齐
  • sum:sum: 字符串 tt 的总哈希值

C++
int get_hash(int l,int r)
{
    return hs[r]-hs[l-1]*pw[r-l+1];
}

计算字符串 ss 中区间子串 [l,r][l,r] 的哈希值,详见上一题

C++
int del_hash(int l,int r,int len)
{
    return get_hash(1,l-1)*pw[len-r]+get_hash(r+1,len);
}

功能:计算字符串 ss 删除区间 [l,r][l,r] 后,剩余字符串的哈希值

原理:将剩余字符串拆分为前半段 [1,l−1][1,l-1] 与后半段 [r+1,len][r+1,len],把前半段的哈希值左移后半段长度位(乘以 pwlen−rpw_{len-r}),再加上后半段的哈希值,完成两段的拼接,即可得到删除后的完整哈希

  • 有了删除操作后,就只需遍历字符串 ss 的每一个位置,计算删除该位置后的哈希值,若与字符串 tt 的哈希相等,则该位置为合法删除位,加入答案,最后按题目要求输出即可

Code

C++
#include<bits/stdc++.h>
#define int long long
#define pii pair<int,int>
using namespace std;
const int N=1e6+10,maxl=1e3+10,inf=0x3f3f3f3f3f3f,mod=1e9+7;
const int p=131;
int sum;
int hs[N],pw[N];
string s,t;
vector<int> ans;
int get_hash(int l,int r)
{
    return hs[r]-hs[l-1]*pw[r-l+1];
}
int del_hash(int l,int r,int len)
{
    return get_hash(1,l-1)*pw[len-r]+get_hash(r+1,len);
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>s>>t;
    int len1=s.size(),len2=t.size();
    s='@'+s;
    t='@'+t;
    pw[0]=1;
    for(int i=1;i<=len1;i++)
    {
        hs[i]=hs[i-1]*p+s[i];
        pw[i]=pw[i-1]*p;
    }
    for(int i=1;i<=len2;i++) sum=sum*p+t[i];
    for(int i=1;i<=len1;i++)
    {
        int tmp=del_hash(i,i,len1);
        if(tmp==sum) ans.push_back(i);
    }
    cout<<ans.size()<<"\n";
    for(int x:ans) cout<<x<<" ";
    return 0;
}

-P3370 【模板】字符串哈希-

思路

Code-暴力

C++
#include<bits/stdc++.h>
#define int long long
#define pii pair<int,int>
using namespace std;
const int N=1e6+10,maxl=1e3+10,inf=0x3f3f3f3f3f3f,mod=1e9+7,LOG=60;
int n,ans;
string s;
map<string,int> mp;
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>n;
    while(n--)
    {
        cin>>s;
        mp[s]++;
    }
    for(auto x:mp)
    {
        if(x.second!=0) ans++;
    }
    cout<<ans;
    return 0;
}

Code-手写哈希

C++
#include<bits/stdc++.h>
#define int unsigned long long
#define pii pair<int,int>
using namespace std;
const int N=1e6+10,maxl=1e3+10,inf=0x3f3f3f3f3f3f,mod=1e6+7,LOG=60;
const int p=131;
int n,ans;
string s;
map<int,int> mp;
void init(string x)
{
    int len=s.size();
    s='@'+s;
    int sum=0;
    for(int i=1;i<=len;i++) sum=sum*p+s[i];
    mp[sum]=1;
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>s;
        init(s);
    }
    for(auto x:mp)
    {
        if(x.second!=0) ans++;
    }
    cout<<ans;
    return 0;
}

-P6739 [BalticOI 2014] Three Friends (Day1)-

思路

我们可以枚举被删掉的点 xx,看剩下的字符串是否可以分成相同的两个字符串,分三种情况讨论点 xx:

  • x=midx=mid(删掉中点)
C++
lt=get_hash(1,x-1);//取左半边哈希值
rt=get_hash(x+1,n);//取右半边哈希值
  • x<midx<mid(删掉左半边里面的一个字符)
C++
lt=del_hash(1,mid,x);//删除位置x之后剩下左半边字符串的哈希值
rt=get_hash(mid+1,n);//取右半边哈希值
  • x>midx>mid(删掉右半边里面的一个字符)
C++
lt=get_hash(1,mid-1);//取左半边哈希值
rt=del_hash(mid,n,x);//删除位置x之后剩下右半边字符串的哈希值

Code

C++
#include<bits/stdc++.h>
#define int long long
#define pii pair<int,int>
using namespace std;
const int N=2e6+10,maxl=1e3+10,inf=0x3f3f3f3f3f3f,mod=1e9+7;
const int p=13331;
int n,mid,idx,cnt;
int lt,rt;
int hs[N],pw[N];
string s;
map<int,int> vis;
int get_hash(int l,int r)
{
    return hs[r]-hs[l-1]*pw[r-l+1];
}
int del_hash(int l,int r,int pos)
{
    return get_hash(l,pos-1)*pw[r-pos]+get_hash(pos+1,r);
}
bool check(int x)
{
    if(x==mid)
    {
        lt=get_hash(1,x-1);
        rt=get_hash(x+1,n);
    }
    else if(x<mid)
    {
        lt=del_hash(1,mid,x);
        rt=get_hash(mid+1,n);
    }
    else
    {
        lt=get_hash(1,mid-1);
        rt=del_hash(mid,n,x);
    }
    return (lt==rt);
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>n>>s;
    int len=s.size();
    s='@'+s;
    mid=(n+1)/2;
    pw[0]=1;
    for(int i=1;i<=len;i++)
    {
        hs[i]=hs[i-1]*p+s[i];
        pw[i]=pw[i-1]*p;
    }
    for(int i=1;i<=n;i++)
    {
        if(check(i))//若删除i后字符串左右两边相等
        {
            idx=i;
            if(vis[rt]>0) continue;//同一个位置只记录一次
            vis[rt]=1;
            cnt++;//统计答案
        }
    }
    if(cnt==0) cout<<"NOT POSSIBLE";
    else if(cnt>1) cout<<"NOT UNIQUE";
    else cout<<((idx<=mid)? s.substr(mid+1):s.substr(1,n/2));//判断删掉的位置小于或大于中点来判断取左半边还是右半边
    return 0;
}

-P10479 匹配统计-

思路

  • 字符串哈希之字符串哈希+二分模板
  • 对字符串 AA 和 BB 分别预处理哈希值,枚举 AA 的每个后缀起点 ii,二分其最长匹配长度,并将答案统计到桶数组中,询问时直接输出桶内值即可
  • 整体复杂度 O(n×log⁡2m+Q)O(n\times\log_2m+Q)

Code

C++
#include<bits/stdc++.h>
#define int long long
#define ull unsigned long long
#define pii pair<int,int>
using namespace std;
const int N=1e6+10,maxl=1e3+10,inf=0x3f3f3f3f3f3f,mod=1e9+7;
const int p=131;
int n,m,q;
int ans[N];
ull hs1[N],hs2[N],pw[N];
string s,t;
ull get_hash1(int l,int r)
{
    return hs1[r]-hs1[l-1]*pw[r-l+1];
}
ull get_hash2(int l,int r)
{
    return hs2[r]-hs2[l-1]*pw[r-l+1];
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>n>>m>>q;
    cin>>s>>t;
    s='@'+s;
    t='@'+t;
    pw[0]=1;
    for(int i=1;i<=n;i++) hs1[i]=hs1[i-1]*p+s[i];
    for(int i=1;i<=m;i++) hs2[i]=hs2[i-1]*p+t[i];
    pw[0]=1ull;
    for(int i=1;i<=(int)2e5;i++) pw[i]=pw[i-1]*p;
    for(int i=1;i<=n;i++)
    {
        int l=-1,r=min(m,n-i+1)+1;
        while(l+1<r)
        {
            int mid=(l+r)/2;
            ull tmp1=get_hash1(i,i+mid-1),tmp2=get_hash2(1,mid);
            if(tmp1==tmp2) l=mid;
            else r=mid;
        }
        if(l==-1) ans[0]++;
        else ans[l]++;
    }
    while(q--)
    {
        int x;
        cin>>x;
        cout<<ans[x]<<"\n";
    }
    return 0;
}

-U577114 M形字符串-

思路

  • 字符串哈希之回文哈希模板
  • 一个字符串是 MM 形字符串,当且仅当:
    • 整个字符串本身是回文
    • 字符串的前半段也是回文
  • 所以我们可以在处理哈希的时候把这个字符串倒着也存一遍哈希值,这样就可以用倒过来的哈希值函数来判断字符串是否回文
  • 若整个字符串与字符串的前半段均回文,则记录答案

Code

C++
#include<bits/stdc++.h>
#define int unsigned long long
#define pii pair<int,int>
using namespace std;
const int N=1e6+10,maxl=1e3+10,inf=0x3f3f3f3f3f3f,mod=1e9+7;
const int p=131;
int n,ans;
int hs1[N],hs2[N],pw[N];
string s;
int get_hash(int l,int r)
{
    return hs1[r]-hs1[l-1]*pw[r-l+1];
}
int hash_get(int l,int r)
{
    return hs2[l]-hs2[r+1]*pw[r-l+1];
}
bool check(int l,int r)
{
    return (get_hash(l,r)==hash_get(l,r));
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>s;
    int len=s.size();
    s='@'+s;
    pw[0]=1;
    for(int i=1;i<=len;i++) hs1[i]=hs1[i-1]*p+s[i];
    for(int i=len;i>=1;i--) hs2[i]=hs2[i+1]*p+s[i];
    for(int i=1;i<=len;i++) pw[i]=pw[i-1]*p;
    for(int i=1;i<=len;i++)
    {
        if(check(1,i) && check(1,(i+1)/2)) ans++;
    }
    cout<<ans;
    return 0;
}

-P3805 【模板】Manacher(24pts)-

思路

回文子串分两类,分别枚举所有可能的中心:

  • 奇数长度回文:中心是单个字符,共 nn 个中心
  • 偶数长度回文:中心在两个字符之间的缝隙,共 n−1n-1 个中心

对每个中心,我们向外扩展找到以它为中心的最长回文半径,再计算总长度更新答案

优化 11:预处理字符串哈希

预处理两个前缀哈希数组:

  • hs1:hs1: 正序前缀哈希,用于计算任意子串正序的哈希值
  • hs2:hs2: 逆序前缀哈希,用于计算任意子串逆序的哈希值

若一个子串正序哈希值=逆序哈希值,说明这个子串回文

优化 22:二分查找

回文扩展满足单调性:

如果向外扩展 midmid 个字符仍然是回文,那么所有小于 midmid 的扩展长度也一定是回文

因此就不用一步步扩展,直接对每个中心二分查找最大半径:

  • 奇数回文:判断 [i−mid,i−1][i-mid,i-1] 与 [i+1,i+mid][i+1,i+mid] 是否对称,二分得到最大半径 ll,回文长度 =l×2+1=l\times2+1
  • 偶数回文:判断 [i−mid+1,i][i-mid+1,i] 与 [i+1,i+mid][i+1,i+mid] 是否对称,二分得到最大半径 ll,回文长度 =l×2=l\times2

最后由 ansans 取最大值即为答案

代码理论复杂度 O(n×log⁡2n)O(n\times\log_2n),但是空间和常数过大,只能拿到部分 24pts24pts

Code

C++
#include<bits/stdc++.h>
#define int unsigned long long
#define pii pair<int,int>
using namespace std;
const int N=2e7+10,maxl=1e3+10,inf=0x3f3f3f3f3f3f,mod=1e9+7;
const int p=131;
int n;
int ans=1;
int hs1[N],hs2[N],pw[N];
string s;
int get_hash(int l,int r)
{
    return hs1[r]-hs1[l-1]*pw[r-l+1];
}
int hash_get(int l,int r)
{
    return hs2[l]-hs2[r+1]*pw[r-l+1];
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>s;
    int n=s.size();
    s='@'+s;
    pw[0]=1;
    for(int i=1;i<=n;i++) hs1[i]=hs1[i-1]*p+s[i];
    for(int i=n;i>=1;i--) hs2[i]=hs2[i+1]*p+s[i];
    for(int i=1;i<=n;i++) pw[i]=pw[i-1]*p;
    for(int i=1;i<=n-1;i++)
    {
        int l=0,r=min(i-1,n-i)+1;
        while(l+1<r)
        {
            int mid=(l+r)/2;
            if(get_hash(i-mid,i-1)==hash_get(i+1,i+mid)) l=mid;
            else r=mid;
        }
        ans=max(ans,l*2+1);
        l=0,r=min(i,n-i)+1;
        while(l+1<r)
        {
            int mid=(l+r)/2;
            if(get_hash(i-mid+1,i)==hash_get(i+1,i+mid)) l=mid;
            else r=mid;
        }
        ans=max(ans,l*2);
    }
    cout<<ans;
    return 0;
}
8.22总结正在补写中