Given a string s, count its palindromic substrings. Substrings at different positions count separately even when their text is identical: "aaa" contains six — three single a's, two "aa"s, and "aaa" itself.
Examples
Example 1:
Input: s = "abc"
Output: 3
Explanation: only the three single characters.
Example 2:
Input: s = "aaa"
Output: 6
Example 3:
Input: s = "aba"
Output: 4
Explanation: a, b, a, and "aba".
Example 4:
Input: s = "aabb"
Output: 6
Constraints
1 <= s.length <= 1000
s consists of lowercase English letters.
Prerequisites
Dynamic programming — being able to say, in one sentence, what a single cell of your table MEANS. Everything else follows from that sentence. Rolling variables: when a state only looks back one or two steps, the table collapses to a couple of numbers.
How to think about it
1. Grow From Every Center, Count Each Match Optimal
Intuition
A palindrome mirrors around its middle: a letter when its length is odd, the gap between two letters when it is even. So stand at a middle and grow outward: each time the letters at both ends match, that is one more palindrome. The first mismatch ends it, because anything wider still holds that unequal pair and cannot read the same both ways. Every palindrome has exactly one middle, so growing from every letter and every gap counts each of them once. Grow out from every center, and count a palindrome each time the ends match.
Algorithm
1. count starts at 0. 2. For every center from the first letter to the last: add grow(s, center, center), what grows around that letter, and grow(s, center, center + 1), what grows around the gap just after it. 3. grow(s, left, right): found starts at 0. While both arms are inside s and s[left] == s[right], that is another palindrome, so found goes up by one; left steps one place left and right one place right. 4. The first mismatch, or an arm off the end, stops it, and grow returns found. 5. After the last center, return count.
Time & Space
Time O(n^2): n letters and n gaps to grow from, and each can grow across the whole string. Space O(1): only a few numbers are kept.
2. The Same Centers, Counted Optimal
Intuition
Identical machinery to Longest Palindromic Substring, with the maximum replaced by a tally: every successful expansion step IS one more palindromic substring. If you solved that problem first, say so — this is a two-line edit, and noticing that is worth more than rederiving it.
Algorithm
1. For each of the 2n-1 centres, expand while the ends match. 2. Count one for every step that matches.