【codeup墓地】2432: 求最长公共子串(串) (字符串哈希)

本文介绍了一种基于哈希的算法,用于寻找两个字符串之间的最长公共子串。通过预计算哈希值和幂次值,算法能有效地比较不同长度的子串,最终找出最长的公共部分。

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

原题链接

#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
using namespace std;

typedef long long int LL;
const int MAX = 10010;
const LL P = 10000019, MOD = 1000000007;

typedef struct Node
{
    string str;//子串
    LL hash_value;///子串哈希值
    int len;//子串长度
}Node;
vector<Node> subS, subT;
string S, T;
Node MAX_LEN = {"", 0, 0};
LL powP[MAX] = {0}, HS[MAX] = {0}, HT[MAX] = {0};

void init(int len)//推算p的指数函数值
{
    powP[0] = 1;
    for(int i=1; i<=len; i++)
    {
        powP[i] = (powP[i-1]*P) % MOD;
    }
}

void calHash(LL H[], string &str)//计算str的从0到i的子串哈希值
{
    H[0] = str[0];
    for(int i=1; i<(int)str.size(); i++)
    {
        H[i] = (H[i-1]*P + str[i]) % MOD;
    }
}

LL calSingleSubHash(LL H[], int i, int j)//推算i到j子串的哈希值
{
    if(!i) return H[j];
    return ((H[j] - H[i-1]*powP[j-i+1]) % MOD + MOD) % MOD;
}

void calSubHash(LL H[], string &str, vector<Node> &subStr)//计算str的每个子串的哈希值
{
    for(int i=0; i<(int)str.size(); i++)
    {
        for(int j=i; j<(int)str.size(); j++)
        {
            LL temp_hash_value = calSingleSubHash(H, i, j);
            Node temp_node = {str.substr(i, j), temp_hash_value, j-i+1};
            subStr.push_back(temp_node);
        }
    }
}

int main()
{
    cin>>S>>T;
    init(max(S.size(), T.size()));
    calHash(HS, S);
    calHash(HT, T);
    calSubHash(HS, S, subS);
    calSubHash(HT, T, subT);
    for(int i=0; i<(int)subS.size(); i++)//根据哈希值判断字符串是否相等
    {
        for(int j=0; j<(int)subT.size(); j++)
        {
            if(subS[i].hash_value == subT[j].hash_value && subS[i].len > MAX_LEN.len)//找到最长子串
            {
                MAX_LEN.hash_value = subS[i].hash_value;
                MAX_LEN.len = subS[i].len;
                MAX_LEN.str = subS[i].str;
            }
        }
    }
    cout<<MAX_LEN.str;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值