最长的回文子串和后缀trie

时间:2012-05-26 16:20:26

标签: string algorithm data-structures palindrome suffix-tree

我在Google上搜索一个众所周知的问题,即:the longest palindromic substring
我发现推荐后缀尝试的链接可以很好地解决问题。
示例SOAlgos
该方法是(据我所知),例如对于字符串S创建SrS反转),然后创建一个通用后缀trie。
然后找到SSr的最长公共字符串,它是从根到最深节点的路径,属于SSr
所以使用后缀尝试方法的解决方案基本上减少到Find the longest common substring问题 我的问题如下:
如果输入字符串为:S = “abacdfgdcaba”那么,Sr = “abacdgfdcaba”最长的公共子字符串为abacd是回文。
所以我的问题是:使用后缀的方法是否错误?我在这里想念/误读吗?

1 个答案:

答案 0 :(得分:4)

是的,通过使用类似LCS的算法找到最长的回文并不是一个好方法,我没有仔细阅读引用的答案,但答案中的这一行是完全错误的:

  

因此字符串中包含的最长的回文恰好是该字符串的最长公共子字符串及其反向

但是如果你读了它并且你有一个反例就不要担心它(99%是正确的),这是常见的错误,但简单的方法如下:

记下字符串(barbapapa),如下所示:#b#a#r#b#a#p#a#p#a#,现在从左到右遍历这个新字符串的每个字符,检查它的左右,检查它是否是回文中心。在最坏的情况下,该算法为O(n ^ 2),并且工作完全正确。但通常会在O(n)中找到回文(肯定证明这在平均情况下很难)。最糟糕的情况是有太多长的回文,如aaaaaa...aaaa

但是有更好的方法需要O(n)时间,该算法的基础是Manacher。相关算法比我在参考答案中看到的更复杂。但我提供的是Manacher算法的基本思想,通过算法的巧妙变化,您可以跳过检查所有左侧和权限(也有使用后缀树的算法)。


P.S:由于我的互联网限制,我看不到您的Algo链接,我不知道它是否正确。

我在OP中加入了我的讨论以澄清算法:

let test it with barbapapa-> #b#a#r#b#a#p#a#p#a#, start from first #
there is no left so it's center of palindrome with length 1.
Now "b",has # in left and # in right, but there isn't another left to match with right 
so it's a center of palindrome with length 3.
let skip other parts to arrive to first "p":
first left and right is # second left and right is "a", third left and
right is # but forth left and right are not equal so it's center of palindrome
of length 7 #a#p#a# is palindrome but b#a#p#a#p is not 
Now let see first "a" after first "p" you have, #a#p#a#p#a# as palindrome and this "a" 
is center of this palindrome with length 11 if you calculate all other palindromes 
length of all of them are smaller than 11

同样使用#是因为考虑了长度均匀的回文。

在新创建的字符串中找到回文中心后,找到相关的回文(通过了解中心及其长度),然后移除#以找出最大的回文。

相关问题