給出兩個由小寫字母組成的字符串,求它們的最長公共子串的長度。
讀入兩個字符串
輸出最長公共子串的長度
1
2
|
yeshowmuchiloveyoumydearmotherreallyicannotbelieveit
yeaphowmuchiloveyoumydearmother
|
27
單個字符串的長度不超過100000
解題思路:後綴自動機
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
char a[100001],b[100001];
int last,cnt,ans,len1,len2,now;
int mx[100010],fa[100010];
int ch[100010][27];
inline int read()
{
char y; int x=0,f=1; y=getchar();
while (y<'0' || y>'9') {if (y=='-') f=-1; y=getchar();}
while (y>='0' && y<='9') {x=x*10+int(y)-48; y=getchar();}
return x*f;
}
void build(int s)
{
int p=last; int np=last=++cnt; mx[np]=mx[p]+1;
while (p!=0 && !ch[p][s]) ch[p][s]=np,p=fa[p];
if (p==0) fa[np]=1;else
{
int q=ch[p][s];
if (mx[q]==mx[p]+1)
{
fa[np]=q;
}else
{
int nq=++cnt; mx[nq]=mx[p]+1;
memcpy(ch[nq],ch[q],sizeof(ch[nq]));
fa[nq]=fa[q];
fa[q]=fa[np]=nq;
while (p!=0 && ch[p][s]==q) ch[p][s]=nq,p=fa[p];
}
}
}
int main()
{
scanf("%s",a); scanf("%s",b);
len1=strlen(a); len2=strlen(b);
cnt=1; last=1;
for (int i=1;i<=len1;++i)
{
build(a[i-1]-'a');
}
now=1;
int ans=-1; int tmp=0;
for (int i=1;i<=len2;++i)
{
int s=b[i-1]-'a';
if (ch[now][s]) ++tmp,now=ch[now][s];else
{
while (!ch[now][s] && now!=0) now=fa[now];
if (now==0) now=1,tmp=0;else
tmp=mx[now]+1,now=ch[now][s];
}
ans=max(ans,tmp);
}
printf("%d",ans);
}