Given a string s
, return the longest palindromic substring in s
.
s
?def longest_palindrome(s: str) -> str:
n = len(s)
if n == 0:
return ""
# Table to store the palindrome status
dp = [[False] * n for _ in range(n)]
# Variables to track the start and end of the longest palindrome
start, max_length = 0, 1
# Every single character is a palindrome
for i in range(n):
dp[i][i] = True
# Check for palindromes of length 2
for i in range(n-1):
if s[i] == s[i+1]:
dp[i][i+1] = True
start = i
max_length = 2
# Check for lengths greater than 2
for length in range(3, n+1): # length is the current substring length
for i in range(n - length + 1):
j = i + length - 1 # Ending index of the current substring
if s[i] == s[j] and dp[i+1][j-1]:
dp[i][j] = True
if length > max_length:
start = i
max_length = length
return s[start:start + max_length]
# Example usage
s = "babad"
print(longest_palindrome(s)) # Output: "bab" or "aba"
dp[i][j]
will be True
if the substring s[i:j+1]
is a palindrome.dp[i][i] = True
).s[i] == s[i+1]
, then mark dp[i][i+1] = True
.s[i] == s[j]
) and whether the substring excluding the ends is a palindrome (i.e., dp[i+1][j-1]
).This solution efficiently finds the longest palindromic substring by balancing between space and time complexity, and ensures correctness via the dynamic programming approach.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?