440/670

440. Palindromic Substrings

Medium

Given a string s, count how many of its substrings are palindromes — strings that read the same forwards and backwards.

A substring is a contiguous run of characters inside s. Occurrences count separately: two substrings with identical characters but different start or end positions are counted as two. Your function receives s and returns the total count as an integer.

Example 1:

Input: s = "abc"

Output: 3

Explanation: Only the three single characters "a", "b", "c" are palindromes — every longer substring has distinct ends.

Example 2:

Input: s = "aaa"

Output: 6

Explanation: Three copies of "a", two copies of "aa", and one "aaa": 3 + 2 + 1 = 6. Identical text at different positions counts every time.

Constraints:

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters only.

Hints:

Every palindrome can be grown outward from its middle. How many possible middles does a string of length n have? (Careful — palindromes of even length have no middle character.)

There are 2n − 1 centers: the n characters and the n − 1 gaps between neighbors. From each center, expand two pointers outward while the end characters match, counting one palindrome per successful expansion.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: s = "abc"

Expected output: 3