代码如下:
#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
*/