问题 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;
}