The "Longest Palindromic Substring" problem can also be solved using Dynamic Programming, which is a method to efficiently solve a complex problem by breaking it down into simpler subproblems and storing the solutions of these subproblems to avoid redundant computations. This approach is particularly useful in this problem to identify palindromic substrings and build upon them. Let's explore how dynamic programming is applied here.
dp[i][j]
is used, where dp[i][j]
is true if the substring from index i
to j
in the given string is a palindrome.dp
with dimensions equal to the length of the string, initialized to false.dp[i][i]
is true for all i
.dp[i][i+1]
is true if the two characters are the same.dp
table in a bottom-up manner. The substring s[i:j]
is a palindrome if s[i] == s[j]
and s[i+1:j-1]
is also a palindrome (i.e., dp[i+1][j-1]
is true).def longest_palindromic_substring(s):
n = len(s)
if n == 0:
return ""
# Initialize DP table
dp = [[False for _ in range(n)] for _ in range(n)]
start = 0
max_length = 1
# Every single character is a palindrome
for i in range(n):
dp[i][i] = True
# Check for two-character palindromes
for i in range(n - 1):
if s[i] == s[i + 1]:
dp[i][i + 1] = True
start = i
max_length = 2
# Check for palindromes longer than 2
for length in range(3, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if s[i] == s[j] and dp[i + 1][j - 1]:
dp[i][j] = True
start = i
max_length = length
return s[start:start + max_length]
In this implementation:
dp
table is filled in a way that ensures that all smaller substrings are processed before the larger ones.