1.Description
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"Output: "bb"
2.Anaylisis
把这道题理解为一个动态规划问题,构造一个二维数组,d[i][j]的值为从字符串下标i到j的子串是否为回文串。
要判断从i到j的子串是不是回文串,只需要判断i+1,j-1的子串是不是回文串,以及s[i] == s[j]即可。
注意构造数组的时候要从右下角开始构造。
3.Code
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
d=[[0 for i in range(0,len(s))] for i in range(0,len(s))]
#print(d)
for i in range(len(s)-1,-1,-1):
for j in range(i,len(s)):
if i == j:
d[i][j]=True
elif j-i == 1:
d[i][j]=(s[i] == s[j])
else:
d[i][j]=((s[i] == s[j]) and d[i+1][j-1])
#abcba
#print(d)
length=1
ans_start,ans_end=0,0
for i in range(0,len(s)):
for j in range(len(s)-1,i-1,-1):
if d[i][j] and j-i+1> length:
ans_start=i
ans_end=j
length=j-i+1
return s[ans_start:ans_end+1]