leetcode 5. 最长回文子串

中心扩展法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
def longestPalindrome(self, s: str) -> str:
ret = ''

for i in range(0, len(s)):
s1 = self.get_palindrome(s, i, i)
s2 = self.get_palindrome(s, i, i+1)

if len(s1) > len(ret):
ret = s1
if len(s2) > len(ret):
ret = s2

return ret

def get_palindrome(self, s, left_index, right_index):
ret = ''

while left_index >= 0 and right_index < len(s) and s[left_index] == s[right_index]:
ret = s[left_index: right_index + 1]
left_index -= 1
right_index += 1

return ret