NeetCode #666LC-5Medium1-D Dynamic ProgrammingBlind 75NC 150NC 250
← Back to All Problems#666 · #5 · Longest Palindromic Substring(最长回文子串)
📌 Problem Statement & Constraints
Given a string
s, return the longest palindromic substring in s. A palindrome reads the same forwards and backwards. Constraints: 1 <= s.length <= 1000, and s consists of digits and English letters.💡 Core Algorithmic Approaches
- A palindrome expands symmetrically around a center, and there are
2n - 1centers:nsingle-character (odd) andn - 1between-character (even) centers. - For each center, expand outward while the two characters match, tracking the longest span found.
- This is O(n^2) time and O(1) extra space, comfortably within the
n <= 1000bound. - Manacher's algorithm achieves O(n), but expand-around-center is simpler and is the standard interview answer.
💻 Benchmark Python3 Implementation
class Solution:
def longestPalindrome(self, s: str) -> str:
start, max_len = 0, 1
def expand(l: int, r: int) -> int:
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return r - l - 1 # length of the palindrome around this center
for i in range(len(s)):
odd = expand(i, i) # odd-length centers
even = expand(i, i + 1) # even-length centers
cur = max(odd, even)
if cur > max_len:
max_len = cur
start = i - (cur - 1) // 2
return s[start:start + max_len]⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n^2): each of the 2n - 1 centers expands at most n steps.
💾 Space Complexity
O(1): only indices plus the returned substring.
⚠️ Interview Pitfalls & Follow-ups
- Checking only odd-length centers: even-length palindromes such as
abbarequire the between-character centers. - Recomputing the left end incorrectly: for a center at
iand lengthL, the left end isi - (L - 1) // 2. - Using a 2-D DP table: it is correct but costs O(n^2) space for no benefit at this input size.
- Assuming a single character is not a palindrome: any length-1 substring is one, so initialise
max_lento 1.