longest-palindromic-substring.py (1004B)
1 def is_palindrome(candidate): 2 left = 0 3 right = len(candidate) - 1 4 while left < right: 5 if candidate[left] != candidate[right]: 6 return False 7 left += 1 8 right -= 1 9 return True 10 11 class Solution: 12 def longestPalindrome(self, s: str) -> str: 13 14 longest = "" 15 16 for i in range(len(s)): 17 left = i 18 right = i 19 while right < len(s) and left >= 0 and is_palindrome(s[left:right + 1]): 20 if (right - left) + 1 > len(longest): 21 longest = s[left:right + 1] 22 left -= 1 23 right += 1 24 25 26 for i in range(len(s)): 27 left = i 28 right = i + 1 29 while right < len(s) and left >= 0 and is_palindrome(s[left:right + 1]): 30 if (right - left) + 1 > len(longest): 31 longest = s[left:right + 1] 32 left -= 1 33 right += 1 34 35 return longest