A string is finite sequence of characters over a non-empty finite set Σ.
In this problem, Σ is the set of lowercase letters.
Substring, also called factor, is a consecutive sequence of characters occurrences at least once in a string.
Now your task is simple, for two given strings, find the length of the longest common substring of them.
Here common substring means a substring of two or more strings.
Input
The input contains exactly two lines, each line consists of no more than 250000 lowercase letters, representing a string.
Output
The length of the longest common substring. If such string doesn't exist, print "0" instead.
Example
Input: alsdfkjfjkdsal fdjskalajfkdsla Output: 3
Notice: new testcases added
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=2e6+10;
const int maxc=28;
char s[maxn];
struct Suffix_Automaton {
int len[maxn * 2]; //最长子串的长度(该节点子串数量=len[x]-len[link[x]])
int link[maxn * 2]; //后缀链接(最短串前部减少一个字符所到达的状态)
int cnt[maxn * 2]; //被后缀连接的数
int nex[maxn * 2][maxc]; //状态转移(尾部加一个字符的下一个状态)(图)
int idx; //结点编号
int last; //最后结点
ll num[maxn * 2]; // enpos数(子串出现数量)
ll a[maxn]; //长度为i的子串出现最大次数
void init() { //初始化
for(int i=1; i<=idx; i++)
link[i] = len[i] = 0,memset(nex[i],0,sizeof(nex[i]));
last = idx = 1; //1表示root起始点 空集
}
//SAM建图
void extend(int c) { //插入字符,为字符ascll码值
int x = ++idx; //创建一个新结点x;
len[x] = len[last] + 1; // 长度等于最后一个结点+1
num[x] = 1; //接受结点子串除后缀连接还需加一
int p; //第一个有C转移的结点;
for (p = last; p && !nex[p][c]; p = link[p])
nex[p][c] = x;//沿着后缀连接 将所有没有字符c转移的节点直接指向新结点
if (!p)link[x] = 1, cnt[1]++; //全部都没有c的转移 直接将新结点后缀连接到起点
else {
int q = nex[p][c]; //p通过c转移到的结点
if (len[p] + 1 == len[q]) //pq是连续的
link[x] = q, cnt[q]++; //将新结点后缀连接指向q即可,q结点的被后缀连接数+1
else {
int nq = ++idx; //不连续 需要复制一份q结点
len[nq] = len[p] + 1; //令nq与p连续
link[nq] = link[q]; //因后面link[q]改变此处不加cnt
memcpy(nex[nq], nex[q], sizeof(nex[q])); //复制q的信息给nq
for (; p&&nex[p][c] == q; p = link[p])
nex[p][c] = nq; //沿着后缀连接 将所有通过c转移为q的改为nq
link[q] = link[x] = nq; //将x和q后缀连接改为nq
cnt[nq] += 2; // nq增加两个后缀连接
}
}
last = x; //更新最后处理的结点
}
ll getSubNum() { //求不相同子串数量
ll ans = 0;
for (int i = 2; i <= idx; i++)
ans += len[i]-len[link[i]]; //一状态子串数量等于len[i]-len[link[i]]
return ans;
}
int run(char s[]){//字符串在SAM上匹配,求最长公共子串的长度
int now=1;
int ans=0,tmp=0;
int ls=strlen(s);
for(int i=0;i<ls;i++){
if(nex[now][s[i]-'a']){
tmp++;
now=nex[now][s[i]-'a'];
}
else{
while(now&&!nex[now][s[i]-'a']) now=link[now];
if(!now){
now=1,tmp=0;
}
else{
tmp=len[now]+1;
now=nex[now][s[i]-'a'];
}
}
if(tmp>ans) ans=tmp;
}
return ans;
}
} sam;
int main(){
scanf("%s",s);
int len=strlen(s);
sam.init();
for(int i=0;i<len;i++) sam.extend(s[i]-'a');
scanf("%s",s);
printf("%d\n",sam.run(s));
return 0;
}