classSolution:deflongestPalindrome(self,s:str) ->str: longest =0 l = r =0for i inrange(len(s)): length, left ,right = self.pali(s, i, i)# 这个写法有点繁杂,只需要返回一个子串,然后选择最长的即可if length > longest: longest = length l = left r = right length, left, right = self.pali(s, i, i+1)if length > longest: longest = length l = left r = rightreturn s[l:r+1]defpali(self,s,l,r): temp_length =0while l >=0and r <len(s)and s[l]== s[r]:if l == r: temp_length +=1else: temp_length +=2 l -=1 r +=1return temp_length, l+1, r-1
时间复杂度:O()
空间复杂度:O()
动态规划
classSolution:deflongestPalindrome(self,s:str) ->str: n =len(s)# dp[i][j]: 字符串s[i:j]是否为回文. 虽然目前是最长, 但状态用了是否同时记录起点和长度 dp = [[True] * n for _ inrange(n)] start =0 res =1for i inrange(n -2, -1, -1):for j inrange(i +1, n): dp[i][j] =Falseif s[i]== s[j]and dp[i+1][j-1]: dp[i][j] =Trueif res < j - i +1: start = i res = j - i +1return s[start: start + res]
# follow up: 移除最多k个, -> 1216classSolution:defvalid_palindrome(self,s:str) ->bool: l =0 r =len(s)-1while l < r:if s[l]== s[r]: l +=1 r -=1else:# 关键是这里: 构建一个判断字符串s从l到r位置是否回文的辅助函数return self.is_valid(s, l+1, r)or self.is_valid(s, l, r-1)returnTruedefis_valid(self,s,l,r):while l < r:if s[l]== s[r]: l +=1 r -=1else:returnFalsereturnTrue
时间复杂度:O(n)
空间复杂度:O(1)
超时
classSolution:defvalidPalindrome(self,s:str) ->bool:if self.is_valid(s):returnTruefor i inrange(len(s)):if self.is_valid(s[:i] + s[i+1:]):returnTruereturnFalsedefis_valid(self,s): l =0 r =len(s)-1while l < r:if s[l]!= s[r]:returnFalse l +=1 r -=1returnTrue