Palindromic Substrings

Medium1-D dynamic programming

Given a string s, return how many of its substrings read the same forwards and backwards. A substring is a run of characters next to each other in s.

Substrings at different positions count separately, even when they hold the same letters. Every single character is a palindrome.

Examples

Example 1
Input:  s = "aba"
Output: 4

a, b, a and aba.

Example 2
Input:  s = "bbbc"
Output: 7

Four single letters, two bb’s at different positions, and bbb.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s holds lowercase English letters only.

Stuck?

Hint 1

Every palindrome has a centre: one character, or the gap between two. Each step outwards that still matches is one more palindrome.

Hint 2

Try all 2n - 1 centres. From each, expand while the two ends match, adding one to the count at every step.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur