leet-code/longest-palindromic-substring/sol.py

25 lines
1.0 KiB
Python
Raw Permalink Normal View History

2022-06-19 21:57:33 +00:00
class Solution:
def longestPalindrome(self, s: str) -> str:
max_palindrome = ""
for idx in range(len(s)):
l, r, odd, even = idx, idx, True, True
while odd or even:
if odd:
if r == len(s) or s[l] != s[r]:
odd = False
if r - l - 1 > len(max_palindrome):
max_palindrome = s[l + 1:r]
if even:
if r == len(s) - 1 or s[l] != s[r + 1]:
even = False
if r - l > len(max_palindrome):
max_palindrome = s[l + 1:r + 1]
if l == 0:
if even and r - l + 2 > len(max_palindrome):
max_palindrome = s[l:r + 2]
elif odd and r - l + 1 > len(max_palindrome):
max_palindrome = s[l:r + 1]
break
l -= 1
r += 1
return max_palindrome