最长回文子串
思路:遍历所有元素,从当前元素向两边扩展,如果两边相同那么可以拓展,回文串长度加2,如此循环。
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
max_len = 0
max_list = ''
for i in range(len(s)):
odd_list, odd_len = self.palindrome(s, i, i)
even_list, even_len = self.palindrome(s, i, i + 1)
if odd_len > even_len:
if odd_len > max_len:
max_len = odd_len
max_list = odd_list
else:
if even_len > max_len:
max_len = even_len
max_list = even_list
return max_list
def palindrome(self, s, left, right):
while left >= 0 and right <= len(s) - 1 and s[left] == s[right]:
left -= 1
right += 1
return s[left+1:right], right - left -1
思路2:dp[left][right] = (right-left<=2) or dp[left+1][right-1]
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
n = len(s)
max_len = 0
max_list = ''
dp = [[False]*n for _ in range(n)]
for r in range(n):
for l in range(r+1):
if s[l] == s[r] and (r-l <= 2 or dp[l+1][r-1]):
dp[l][r] = True
if r-l+1 >= max_len:
max_len = r-l+1
max_list = s[l:r+1]
return max_list