Blind 75 · #53 · 1-D Dynamic Programming

Palindromic Substrings

MediumExpand around centreTime O(n²)Space O(1)

Palindromic Substrings is a medium 1-D Dynamic Programming problem from the Blind 75. The key pattern is expand around centre, and a good solution runs in O(n²) time.

Problem

Count all palindromic substrings, including identical text at different positions.

Examples

Example 1

Input

"ababa"

Output

9

Example 2

Input

"dog"

Output

3

Example 3

Input

"zzz"

Output

6

Approach

Expand from all 2n − 1 centres and count every successful step outward as one palindrome.

PatternExpand around centre
TimeO(n²)
SpaceO(1)

Watch out for

Each single character counts as a palindrome.

More 1-D Dynamic Programming problems