This question on LeetCode is similar to the 516. Longest Palindromic Subsequence. Therefore, I'm also using the same dynamic programming solution to solve. However, there are slight differences. Here, we are using the dp array to store the boolean value indicating whether the substring from index i to j is a palindromic substring.
Question
Solution
We create a 2D-array dp, where dp[i][j]
contains the boolean answer that the current substring formed from index i
to j
in s
is palindromic or not.
There are three conditions following:
- i == j
It is always true that single-word substrings are palindromes - s[i] == s[j]
If the substring between indices i+1 and j-1 is a palindrome, then we can conclude that the current substring is also a palindrome. However, we must be cautious when two-word substrings like substringdd
in the string(bab'dd')
is palindromes as well cause the default value of boolean array is false. So, the dp[4][3] will get false in this situation. That reason why I addedj - i == 1
to the conditional expression. - s[i] != s[j]
If s[i] is not equal to s[j], then this substring cannot be a palindrome.
1 | //Time complexity: O(n^2) |