最直观的做法,时间,空间复杂度都是O(2^n)
class Solution:
def longestPalindrome(self, s: str) -> str:
dp = [[0 for i in range(len(s))] for j in range(len(s))]
longestSubStr = "" # 存储最长回文子串
longestLen = 0 # 最长回文子串的长度、
for j in range(len(s)):
for i in range(j+1):
if j-i <= 1:
if s[i]==s[j]:
dp[i][j]=1
if longestLen<j-i+1:
longestLen = j-i+1
longestSubStr = s[i:j+1]
elif j-i>1:
if s[i]==s[j] and dp[i+1][j-1] == 1:
dp[i][j] = 1
if longestLen < j-i+1:
longestLen = j-i+1
longestSubStr = s[i:j+1]
return longestSubStr