Last active
December 23, 2015 02:29
-
-
Save daeyun/6567062 to your computer and use it in GitHub Desktop.
find the length of the longest palindrome subsequence in O(n^2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
class LongestPalindrome: | |
def longestPalindrome(self, string): | |
self.string = string | |
self.LP = {} | |
return self.longestPalindrome_(0, len(self.string) - 1) | |
def longestPalindrome_(self, i, j): | |
if (i, j) in self.LP: | |
return self.LP[(i, j)] | |
elif j == i: | |
return 1 | |
elif j < i: | |
return 0 | |
else: | |
if self.string[i] == self.string[j]: | |
length = self.longestPalindrome_(i+1, j-1) + 2 | |
else: | |
length = max(self.longestPalindrome_(i+1, j), | |
self.longestPalindrome_(i, j-1)) | |
if (i, j) not in self.LP: | |
self.LP[(i, j)] = length | |
return length | |
f = LongestPalindrome() | |
assert f.longestPalindrome("12321") == 5 | |
assert f.longestPalindrome("123321") == 6 | |
assert f.longestPalindrome("1233321") == 7 | |
assert f.longestPalindrome("01233321") == 7 | |
assert f.longestPalindrome("12333210") == 7 | |
assert f.longestPalindrome("1203303210") == 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment