palindromic-substrings.sh — zsh

Palindromic Substrings

medium
stringsdynamic-programming

Count all palindromic contiguous substrings of s. Substrings with identical text at different positions count separately, and every single character is a palindrome.

Input / output

  • Input: s: string
  • Output: integer count

Examples

  1. "abc" returns 3.
  2. "aaa" returns 6: three single characters, two "aa" substrings, and one "aaa".

Constraints

  • 1 <= s.length <= 1,000
  • s contains lowercase English letters.

Follow-up Explain why expanding around 2n - 1 centers is quadratic time but constant extra space.

Examples
Example 1
Input: s = "abc"
Output: 3
Example 2
Input: s = "aaa"
Output: 6
Example 3
Input: s = "aba"
Output: 4
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.