字符串 hash + poj 2774 (hash+二分)

本文介绍了一种使用二分查找结合哈希值的方法来寻找两个字符串之间的最长公共子串。通过将其中一个字符串的所有可能子串哈希值存入容器,并对另一个字符串进行相同操作后利用二分查找来验证是否存在公共子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  这题是求最长公共子串的长度,用二分求,check mid的时候,把s1的全部长度为mid的子串的hash值存入ihash容器,然后再求依次求出S2的长度为mid的子串的hash值,再用二分查找在ihash里找,找到了说明存在长度为mid的公共子串,找不到就存在。

这题存s1的hash值的时候用数组存就wa,就vector就ac,很奇怪

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
#define ull unsigned long long
const int maxn=100000+10;
ull ba[maxn],base=131;
vector<ull>ihash;
string s1,s2;
int len1,len2,ans;

bool check(int len)
{
    ihash.clear();
    ull tmp=0;
    for(int i=1;i<=len;i++)//求出s1里全部长度为len的子串的hash值
    {
        tmp=tmp*base+s1[i];
    }
    ihash.push_back(tmp);
    for(int i=2;i<=len1-len+1;i++)//求出s1里全部长度为len的子串的hash值
    {
        tmp=(tmp-s1[i-1]*ba[len-1])*base+s1[i+len-1];
        ihash.push_back(tmp);
    }
    sort(ihash.begin(),ihash.end());//为后面二分查找做准备
    //cout<<"s1 ihash:"<<endl;
    //for(int i=0;i<tot;i++)
        //cout<<ihash[i]<<" ";
    tmp=0;
    for(int i=1;i<=len;i++)//求出s2里全部长度为len的子串的hash值
    {
        tmp=tmp*base+s2[i];
    }
    //cout<<"s2 ihash:"<<endl;
    //cout<<tmp<<" ";
    if(binary_search(ihash.begin(),ihash.end(),tmp))
    {
        //cout<<"find:"<<tmp<<endl;
        return true;
    }
    for(int i=2;i<=len2-len+1;i++)
    {
        tmp=(tmp-s2[i-1]*ba[len-1])*base+s2[i+len-1];
        //cout<<tmp<<" ";
        if(binary_search(ihash.begin(),ihash.end(),tmp))
        {
           // cout<<"find:"<<tmp<<endl;
            return true;
        }


    }
    return false;


}
int main()
{
    cin>>s1>>s2;
    len1=s1.size();
    len2=s2.size();
    //cout<<s1<<endl<<s2<<endl<<len1<<" "<<len2<<endl;
    s1=" "+s1;
    s2=" "+s2;
    int low=0,up=min(len1,len2),mid;
    ba[0]=1;
    for(int i=1;i<=up;i++)
        ba[i]=ba[i-1]*base;

    ans=-1;
    while(low<=up)
    {
        mid=(low+up)>>1;
        //cout<<"mid:"<<mid<<"  low:"<<low<<"  up:"<<up<<endl;
        if(check(mid))
        {

            ans=mid;
            low=mid+1;
        }
        else
            up=mid-1;
        //system("pause");
    }
    cout<<ans<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值