题目:
给你一个字符串 s,找到 s 中最长的回文子串。
解答:
方法一:暴力解法,超时
class Solution:
def isParlindrome(self,s):
n=len(s)
for i in range(n//2):
if s[i]!=s[n-1-i]:
return 0
return n
def longestPalindrome(self, s: str) -> str:
#暴力解法
n=len(s)
res=0
for i in range(n):
for j in range(i+1,n+1):
tmp=self.isParlindrome(s[i:j])
if tmp>res:
res=tmp
ans=s[i:j]
return ans
方法二:动态规划
class Solution:
def longestPalindrome(self, s: str) -> str:
#dp[i][j]:表示区间范围[i,j] (注意是左闭右闭)的子串是否是回文子串,如果是dp[i][j]为true,否则为false
n=len(s)
#res记录当前最长回文子串的长度
res=0
dp=[[False]*n for _ in range(n)]
#从下到上,从左到右
for i in range(n-1,-1,-1):
for j in range(i,n):
if s[i]==s[j]:
if j-i<=2:
dp[i][j]=True
elif dp[i+1][j-1]:
dp[i][j]=True
if dp[i][j]:
tmp=j-i+1
if tmp>res:
res=tmp
ans=s[i:j+1]
return ans