on-internet
← Community

How can I optimize a Python function to find the longest palindrome in a string?

Stack Overflow ·

I've been working on a Python function to find the longest palindromic substring within a given string. My current approach works, but it feels inefficient and struggles with longer strings. I'm looking for ways to optimize it. Here's what I have so far: def longest_palindrome(s): def expand_around_center(left, right): while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return s[left + 1:right] if not s: return "" longest = "" for i in range(len(s)): odd_palindrome = expand_around_center(i, i) even_palindrome = expand_around_center(i, i + 1) longest = max(longest,

Comments

Sign in or sign up to comment and upvote.

No comments yet.