0005. Longest Palindromic Substring
Medium | String + DP | 80 ms (99.34%), 13.5 MB (92.93%)
Last updated
Was this helpful?
Medium | String + DP | 80 ms (99.34%), 13.5 MB (92.93%)
Last updated
Was this helpful?
Source: GitHub:
Given a string s
, return the longest palindromic substring in s
.
A two-dimension array is initialized to store whether s[j:i]
is a palindromic string by recording as dp[i][j] = True
. Then, we iterate the input string by a nested for loop which range is from i = len(s)
and j = i+1
.
In each iteration, there are three different conditions to help us check palindrome:
if i == j
, dp[i][j] = True
if i == j + 1
, dp[i][j] = s[i] == s[j]
else
, dp[i][j] = (dp[i-1][j+1] and s[i] == s[j])
Note that condition 3 checks whether the shrunk string s[j+1:i-1]
is a palindrome string and whether s[i] == s[j]