loading

Palindromic Substrings — Step-by-Step Visualization

mediumLeetCode #647StringDynamic Programming

Given a string `s`, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string.

Algorithm Pattern

Expand Around Center

Key Idea

A palindrome can have an odd length (one center character) or an even length (two center characters). For every possible center in the string (there are `2n - 1`), we can 'expand' outwards as long as the characters match and we are within boundaries. Each step of a successful expansion counts as a new palindromic substring.

Step-by-Step Approach

  1. Initialize `count = 0`.
  2. Iterate through the string, treating each character and each pair of adjacent characters as a potential center.
  3. For each center, expand outwards: `left--` and `right++`.
  4. If `s[left] == s[right]`, increment `count` and continue expansion.
  5. Return the total `count`.

Common Gotchas

  • Single characters are always palindromes.
  • There are `n` odd-length centers and `n-1` even-length centers, totaling `2n - 1`.

Related Problems