max_length = 1 begin = 0 dp = [[False]*s_length for _ inrange(s_length)]
for i inrange(s_length): dp[i][i] = True
for L inrange(2,s_length+1):
for i inrange(s_length):
j = L + i - 1
if j >=s_length: break
if s[i] != s[j]: dp[i][j] = False else: if j - i<3: dp[i][j] =True else: dp[i][j] = dp[i+1][j-1]
if dp[i][j] and j-i+1 > max_length: max_length = j-i+1 begin = i
return s[begin : begin + max_length]
复杂度
时间复杂度:\(O(n^2)\)
空间复杂度:\(O(n^2)\)
2、中心扩展法
该方法可以理解成第一种方法的逆向思维:即以最短的回文串不断左右扩展,找到最长的回文串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: defexpandAroundCenter(self, s, left, right): while left >= 0and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return left + 1, right - 1
deflongestPalindrome(self, s: str) -> str: start, end = 0, 0 for i inrange(len(s)): left1, right1 = self.expandAroundCenter(s, i, i) left2, right2 = self.expandAroundCenter(s, i, i + 1) if right1 - left1 > end - start: start, end = left1, right1 if right2 - left2 > end - start: start, end = left2, right2 return s[start: end + 1]
classSolution: defexpand(self, s, left, right): while left >= 0and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return (right - left - 2) // 2
deflongestPalindrome(self, s: str) -> str: end, start = -1, 0 s = '#' + '#'.join(list(s)) + '#' arm_len = [] right = -1 j = -1 for i inrange(len(s)): if right >= i: i_sym = 2 * j - i min_arm_len = min(arm_len[i_sym], right - i) cur_arm_len = self.expand(s, i - min_arm_len, i + min_arm_len) else: cur_arm_len = self.expand(s, i, i) arm_len.append(cur_arm_len) if i + cur_arm_len > right: j = i right = i + cur_arm_len if2 * cur_arm_len + 1 > end - start: start = i - cur_arm_len end = i + cur_arm_len return s[start+1:end+1:2]