1

Possible Duplicate:
how to find longest palindromic subsequence?

Longest palindrome subsequence.
A palinadrome is a nonempty string over some alphabet that reads the same forward and backward. Examples of palindromes are all strings of length 1, civic, racecar, and aibohphobia(fear of palindromes). Give an efficent algorithm to find the longest palindrome that is a subsequence of a given input string. For example, given the input "character", your algorithm should return "caac".

Now, I know how to get the length of the result. How can I get the sequence of the result ?

def mylongest(self, i, j):
    if j - i <= 1:
        return j-i
    else:
        if self.sequence[i] == self.sequence[j]:
            return self.mylongest(i+1,j-1) + 2
        else:
            return max (self.mylongest(i+1, j), self.mylongest(i, j-1))
Community
  • 1
  • 1
xiaoke
  • 253
  • 1
  • 4
  • 9
  • 1
    Algorithm for this was discussed here: http://stackoverflow.com/questions/4790522/how-to-find-longest-palindromic-subsequence – ernie Sep 14 '12 at 19:14
  • 3
    IS this homework from here? www.cs.usfca.edu/~galles/cs673/hw7.btreedp.pdf? – ernie Sep 14 '12 at 19:15
  • 1
    actually, 'carac' is longer than 'caac' – stark Sep 14 '12 at 19:36
  • Also see http://stackoverflow.com/questions/6132688/finding-the-longest-palindrome-subsequence-with-less-memory – James Waldby - jwpat7 Sep 14 '12 at 23:47
  • Those questions are only get the length of the result, which I show above. I want to output the palindrome sequence. I have been think about it for 4 hours. But I still not figure it out. – xiaoke Sep 15 '12 at 03:34

1 Answers1

3

using itertools.combinations():

In [2]: from itertools import combinations

In [7]: strs="character"

In [8]: for y in range(len(strs)-1,1,-1):
   ...:     for x in combinations(strs,y):
   ...:         if ''.join(x)==''.join(x)[::-1]:
   ...:             print ''.join(x)
   ...:             break
   ...:             
   ...:             
carac
caac
chc
cc
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 1
    You are checking all 2^n combinations, I hope it's not the most efficient algorithm... It's definitely the least efficient algorithm. – zmbq Sep 14 '12 at 21:22
  • 3
    I think we can use dynamic program to solve this problem by O(n^2). – xiaoke Sep 15 '12 at 04:07