I was solving Longest Palindrome in a String problem, where we are searching for the longest substring forming a palindrome. My code for the above is :
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));
}
Now, I am curious to know that if instead of finding the longest substring, we make a palindrome choosing random characters (just one instance of each) from the string but in the same sequence as in String. Is it possible to do this in polynomial time?