题目描述:
给定一个字符串
s
,找到
s
中最长的回文子串。你可以假设
s
的最大长度为 1000。
示例 1:
输入: "babad" 输出: "bab" 注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd" 输出: "bb"
Solution(转自LeetCode官方题解):
CODE:
class Solution:
def longestPalindrome(self,s):
'''
:param s:str
:return: str
'''
longest = 0
len_s = len(s)
dp = [[0 for i in range(len_s)] for i in range(len_s)]
for j in range(0,len_s):
for i in range(0,j+1):
if j-i <= 1:
if s[i] == s[j]:
dp[i][j] = 1
if longest < j-i+1:
longest = j-i+1
sublongeststr = s[i:j+1]
else:
if j-i > 1:
if s[i] == s[j] and dp[i+1][j-1]:
dp[i][j] = 1
if longest < j-i+1:
longest = j-i+1
sublongeststr = s[i:j+1]
return sublongeststr