Longest Palindromic Substring
Examples
Example 1:
Input: s = "ababd"
Output: "bab"
Explanation:
Example 2:
Input: s = "abbc"
Output: "bb"
Example 1:
Input: s = "ababd"
Output: "bab"
Explanation:
Example 2:
Input: s = "abbc"
Output: "bb"
Given a string s, return the longest substring of s that is a palindrome.
A palindrome is a string that reads the same forward and backward.
If there are multiple palindromic substrings that have the same length, return any one of them.
Both "aba" and "bab" are valid answers.
1 <= s.length <= 1000s contains only digits and English letters.Expand around every possible center. For each index, expand for odd-length and even-length palindromes and track the longest span. Return the substring defined by the best span.
Every palindrome is centered at either a character (odd length) or between two characters (even length). Expanding around all centers explores every palindrome and keeps the maximum length found.
O(n^2)O(1)class Solution:
def longestPalindrome(self, s: str) -> str:
if not s:
return ""
start, end = 0, 0
def expand(l: int, r: int) -> tuple[int, int]:
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return l + 1, r - 1
for i in range(len(s)):
l1, r1 = expand(i, i)
l2, r2 = expand(i, i + 1)
if r1 - l1 > end - start:
start, end = l1, r1
if r2 - l2 > end - start:
start, end = l2, r2
return s[start:end + 1]