Longest Palindromic Substring in Python

class Solution:
    def longestPalindrome(self, s: str) -> str:
        # Initialize variables to store the start and end of the longest palindrome found
        longest_start = 0
        longest_length = 0

        # Define a helper function to expand around the center and find the longest palindrome
        def expand_around_center(left: int, right: int):
            # Access the variables declared outside this function
            nonlocal longest_start, longest_length

            # Expand around the center as long as the substring is a palindrome
            while left >= 0 and right < len(s) and s[left] == s[right]:
                # Check if the current palindrome is longer than the longest found so far
                if (right - left + 1) > longest_length:
                    # Update the longest palindrome's start position and length
                    longest_start = left
                    longest_length = right - left + 1
                # Expand outwards
                left -= 1
                right += 1

        # Iterate over the string to consider each character as the center of a palindrome
        for i in range(len(s)):
            # For odd length palindromes, the center is a single character
            expand_around_center(i, i)
            # For even length palindromes, the center is between two characters
            expand_around_center(i, i + 1)

        # Slice the original string from the start of the longest palindrome to its end and return it
        return s[longest_start : longest_start + longest_length]

PrevNext