codeup 求最长公共子串(字符串hash思想)

问题 A: 求最长公共子串(串)

[命题人 : 外部导入]
时间限制 : 1.000 sec 内存限制 : 128 MB

题目描述

求采用顺序结构存储的串s和串t的一个最长公共子串,若没有则输出false,若最长的有多个则输出最先出现的那一串。

输入

输入两个字符串

输出

输出公共子串

样例输入 Copy

abcdef
adbcef

样例输出 Copy

bc
原题地址

#include <iostream>
#include <vector>
#include <algorithm>
#include <string.h>
#include <queue>
#include <stack>
using namespace std;
const int P=1e7+19;
const int mod=1e9+7;
const int maxn=1e5+10;
vector<pair<int, string >> p1,p2;
string str1,str2;
long long  H1[maxn],powP[maxn],H2[maxn];
void init(){
    int k=max(str1.length(),str2.length());
    powP[0]=1;
    for(int i=1;i<=k;i++){
        powP[i]=(powP[i-1]*P)%mod;
    }
}
void calH(string str,long long  H[maxn]){
    H[0]=str[0];
    for(int i=1;i<str.length();i++){
        H[i]=(H[i-1]*P+str[i])%mod;
    }
}
void calsub(string str,long long H[maxn],vector<pair<int,string>> &pr){
    pair<int ,string > ps;
    for(int i=0;i<str.length();i++){
        for(int j=i;j<str.size();j++){
            if(i==0) {
                ps.first=H[j];ps.second="";
                for(int k=i;k<=j;k++) ps.second+=str[k];
                pr.push_back(ps);
            }
            else {
                ps.first=((H[j]-H[i-1]*powP[j-i+1])%mod + mod) % mod;
                ps.second="";
                for(int k=i;k<=j;k++) ps.second+=str[k];
                pr.push_back(ps);
            }
        }
    }
}
void getmax(){
    int res=0;
    string temp;
    for(int i=0;i<p1.size();i++){
        for(int j=0;j<p2.size();j++){
            int m=p1[i].second.length();
            if(p1[i].first == p2[j].first && m>res) {
                res=m; 
                temp=p1[i].second;
            }
        }
    }
    if(res==0) cout<<"false";
    else cout<<temp<<endl;
}
int main(){
    getline(cin,str1);
    getline(cin,str2);
    init(); //初始化powP;
    calH(str1,H1); //计算每个str的以j结尾的hash值
    calH(str2,H2);
    calsub(str1,H1,p1);
    calsub(str2,H2,p2);
    getmax();
    system("pause");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值