Solution: Palindromic Substrings
Explore how to count the number of palindromic substrings in a string using dynamic programming. Understand the step-by-step approach of building a lookup table to avoid redundant checks, improve efficiency from a naive cubic solution to a quadratic time algorithm, and grasp how to apply base cases for substrings of length one and two. This lesson equips you with an optimized method to solve palindromic substring problems in C++ with clear insight into time and space trade-offs.
Statement
Given a string, s, return the number of palindromic substrings contained in it. A substring is a contiguous sequence of characters in a string. A palindrome is a phrase, word, or sequence that reads the same forward and backward.
Constraints:
s.lengthsconsists of only lowercase English characters.
Solution
So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which to follow based on considerations such as time complexity and implementation constraints.
Naive approach
A naive approach to this problem is to find all possible substrings and count the number of palindromic substrings. For example, consider the string “deed”. The number of substrings contained in “deed” is 10: “d”, “e”, “e”, “d”, “de”, “ee”, “ed”, “dee”, “eed”, and “deed”. Out of these 10 substrings, six are palindromes: “d”, “e”, “e”, “d”, “ee”, and “deed”. Therefore, the number of palindromic substrings in “deed” is six.
We get the required result, but at what cost? Since we’re checking every possible substring, the total number of substrings in a string of length