Skip to content

Commit

Permalink
dp
Browse files Browse the repository at this point in the history
  • Loading branch information
idf committed Nov 7, 2015
1 parent 2a8040b commit ab3f130
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions Longest Palindromic Substring.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,26 @@ class Solution:
def longestPalindrome(self, s):
"""
O(n) Manacer's algorithm
O(n^2) dp
:param s:
:return:
"""
n = len(s)
pa = [[False for _ in xrange(n+1)] for _ in xrange(n)]
for i in xrange(n):
pa[i][i] = True
pa[i][i+1] = True

maxa = (0, 1)
for i in xrange(n-2, -1, -1):
for j in xrange(i+2, n+1):
pa[i][j] = pa[i+1][j-1] and s[i] == s[j-1]
if pa[i][j] and j-i > maxa[1]-maxa[0]:
maxa = (i, j)

return s[maxa[0]:maxa[1]]


if __name__ == "__main__":
assert Solution().longestPalindrome("abcdzdcab") == "cdzdc"

0 comments on commit ab3f130

Please sign in to comment.