算法笔记-12.1-字符串hash进阶

代码如下:

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

const int maxn=1010;
typedef long long LL;
const LL MOD = 1000000007;
const LL P = 10000019;

LL powp[maxn],h1[maxn]={0},h2[maxn]={0};  //(p^i)%mod str1,str2的hash
vector< pair<int,int> > pr1,pr2;    //str1<字串hash值 字串长度>

void init(int len)
{
    powp[0]=1;
    for(int i=1;i<=len;i++)
    {
        powp[i]=(powp[i-1]*P)%MOD;
    }
}

void calh(LL (&h)[maxn],string &s)
{
    h[0]=s[0]-'a';
    for(int i=1;i<s.length();i++)
    {
        h[i]=(h[i-1]*P+(s[i]-'a'))%MOD;
    }
}

int cal_single_sub(LL h[],int st,int ed)
{
    if(st==0)return h[ed];
    return ((h[ed]-h[st-1]*powp[ed-st+1])%MOD+MOD)%MOD;   ///记住!!!!!!!!!!!!!!
}
int cal_sub(LL h[],int len,vector<pair<int,int> >&pr)
{
    for(int i=0;i<len;i++)
    {
        for(int j=i;j<len;j++)
        {
            int hash_value=cal_single_sub(h,i,j);
            pr.push_back(make_pair(hash_value,j-i+1));
        }
    }
}

int getmax()
{
    int ans=0;
    for(int i=0;i<pr1.size();i++)
    {
        for(int j=0;j<pr2.size();j++)
        {
            if(pr1[i].first==pr2[j].first)
            {
                ans=max(ans,pr1[i].second);
            }
        }
    }
    return ans;
}
int main()
{
    string s1,s2;
    getline(cin,s1);
    getline(cin,s2);
    init(max(s1.length(),s2.length()));
    calh(h1,s1);
    calh(h2,s2);
    cal_sub(h1,s1.length(),pr1);
    cal_sub(h2,s2.length(),pr2);
    int ans=getmax();
    cout<<ans<<endl;
    system("pause");
    return 0;
}


/*
iloveyou
youdontloveme

*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值