C++ 使用后缀数组实现最长公共子串
我用它来计算后缀数组和最长的公共前缀 我需要计算两个字符串之间最长的公共子字符串 为此,我连接字符串,C++ 使用后缀数组实现最长公共子串,c++,arrays,suffix-array,longest-substring,longest-prefix,C++,Arrays,Suffix Array,Longest Substring,Longest Prefix,我用它来计算后缀数组和最长的公共前缀 我需要计算两个字符串之间最长的公共子字符串 为此,我连接字符串,A#B,然后使用 我有后缀数组sa[]和LCP[]数组 最长的公共子字符串是LCP[]数组的最大值 为了找到子字符串,唯一的条件是,在公共长度的子字符串中,字符串B中第一次出现的子字符串应该是答案 为此,我保持LCP的最大值[]。如果LCP[curr\u index]==max,则我确保子字符串B的左\u index小于左\u index的上一个值 然而,这种方法并没有给出正确的答案。故障在哪里
A#B
,然后使用
我有后缀数组sa[]
和LCP[]
数组
最长的公共子字符串是LCP[]
数组的最大值
为了找到子字符串,唯一的条件是,在公共长度的子字符串中,字符串B中第一次出现的子字符串应该是答案
为此,我保持LCP的最大值[]。如果LCP[curr\u index]==max
,则我确保子字符串B的左\u index
小于左\u index
的上一个值
然而,这种方法并没有给出正确的答案。故障在哪里
max=-1;
for(int i=1;i<strlen(S)-1;++i)
{
//checking that sa[i+1] occurs after s[i] or not
if(lcp[i] >= max && sa[i] < l1 && sa[i+1] >= l1+1 )
{
if( max == lcp[i] && sa[i+1] < left_index ) left_index=sa[i+1];
else if (lcp[i] > ma )
{
left_index=sa[i+1];
max=lcp[i];
}
}
//checking that sa[i+1] occurs after s[i] or not
else if (lcp[i] >= max && sa[i] >= l1+1 && sa[i+1] < l1 )
{
if( max == lcp[i] && sa[i] < left_index) left_index=sa[i];
else if (lcp[i]>ma)
{
left_index=sa[i];
max=lcp[i];
}
}
}
max=-1;
对于(int i=1;i=max&&sa[i]=l1+1)
{
如果(max==lcp[i]&&sa[i+1]ma)
{
左_指数=sa[i+1];
max=lcp[i];
}
}
//检查sa[i+1]是否在s[i]之后出现
否则如果(lcp[i]>=max&&sa[i]>=l1+1&&sa[i+1]ma)
{
左_指数=sa[i];
max=lcp[i];
}
}
}
好的,这个问题来自一个编程竞赛,在社论发布之前讨论正在进行的竞赛的编程问题不应该。。。。虽然我给了你一些见解,因为我用后缀数组得到了错误的答案。然后我使用后缀自动机,它让我接受
后缀数组在O(nlog^2n)
中工作,而后缀自动机在O(n)
中工作。所以我的建议是使用后缀自动机,你肯定会被接受。
如果你能编码,你肯定会编码
在codchef论坛中还发现:
Try this case
babaazzzzyy
badyybac
The suffix array will contain baa... (From 1st string ) , baba.. ( from first string ) , bac ( from second string ) , bad from second string .
So if you are examining consecutive entries of SA then you will find a match at "baba" and "bac" and find the index of "ba" as 7 in second string , even though its actually at index 1 also .
Its likely that you may output "yy" instead of "ba"
同时处理约束…在第二个字符串上找到的第一个最长公共子字符串应写入输出…对于后缀自动机来说非常容易。祝你好运