【题目】
示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。
示例 2:
输入:s = “cbbd”
输出:“bb”
提示:
1 <= s.length <= 1000
s 仅由数字和英文字母组成
【代码】
执行用时:612 ms, 在所有 Python3 提交中击败了89.65% 的用户
内存消耗:15.1 MB, 在所有 Python3 提交中击败了68.52% 的用户
通过测试用例:180 / 180
class Solution:
def longestPalindrome(self, s: str) -> str:
max_len=1
ans_str=s[0]
n=len(s)
if s==s[::-1]:
return s
for i in range(n):
pos=1
while i-pos>=0 and i+pos<n:
if s[i-pos:i+pos+1]==s[i-pos:i+pos+1][::-1]:
if 2*pos+1>max_len:
ans_str=s[i-pos:i+pos+1]
max_len=len(ans_str)
else:
break
pos+=1
pos=0
while i-pos>=0 and i+pos+1<n:
if s[i-pos:i+pos+2]==s[i-pos:i+pos+2][::-1]:
if 2*(pos+1)>max_len:
ans_str=s[i-pos:i+pos+2]
max_len=len(ans_str)
pos+=1
else:
break
return ans_str
【方法2】动态规划法
执行用时:7004 ms, 在所有 Python3 提交中击败了30.32% 的用户
内存消耗:22.9 MB, 在所有 Python3 提交中击败了22.46% 的用户
通过测试用例:180 / 180
class Solution:
def longestPalindrome(self, s: str) -> str:
n=len(s)
max_len=1
max_index=(0,0)
dp=[[0]*n for _ in range(n)]
for col in range(1,n):
for row in range(col):
if (col-row+1)<=3:
dp[row][col]=(s[row]==s[col])
if s[row]==s[col]:
if max_len<col-row+1:
max_len=col-row+1
max_index=(row,col)
else:
dp[row][col]=(s[row]==s[col]) and dp[row+1][col-1]
if dp[row][col] and max_len<col-row+1:
max_len=col-row+1
max_index=(row,col)
return s[max_index[0]:max_index[1]+1]