【发布时间】:2015-04-25 17:48:03
【问题描述】:
我正在解决字符串问题中的最长回文,我们正在寻找形成回文的最长子字符串。我上面的代码是:
private static int palindrome(char[] ch, int i, int j) {
// TODO Auto-generated method stub
if (i == j)
return 1;
// Base Case 2: If there are only 2 characters and both are same
if (ch[i] == ch[j] && i + 1 == j)
return 2;
// If the first and last characters match
if (ch[i] == ch[j])
return palindrome(ch, i + 1, j - 1) + 2;
// If the first and last characters do not match
return max(palindrome(ch, i, j - 1), palindrome(ch, i + 1, j));
}
现在,我很想知道,如果我们不是寻找最长的子字符串,而是创建一个回文,从字符串中选择随机字符(每个字符只有一个实例),但顺序与 String 中的相同。是否可以在多项式时间内做到这一点?
【问题讨论】:
-
我不确定我是否理解你的问题。对于字符串“abcde”,您会生成回文“c”还是“abcdedcba”?
-
@RavindraHV 看到问题的最后一部分。我编辑了它。
-
我假设你想要尽可能长的回文?
-
@maraca 正确的术语是子序列:en.wikipedia.org/wiki/Subsequence
-
我认为这可以通过对字符串及其反向应用最长公共子序列算法来解决。
标签: java string algorithm palindrome