Example 1
- Input
- s = "abc"
- Output
- 3
The three single characters at indices 0, 1, and 2 are palindromes. The other candidates ab, bc, and abc have unequal outer letters, so the count is 3.
A substring reads the same forward and backward when its outer characters match all the way inward. Count every contiguous slice of the input string that has this property.
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, and a substring is a contiguous block of characters inside s.
Every single character counts as a palindrome of length 1, and overlapping substrings at different positions are counted separately even when they look identical.
Return the total count across all start and end positions.
1 <= s.length <= 1000s consists of lowercase English letters.The three single characters at indices 0, 1, and 2 are palindromes. The other candidates ab, bc, and abc have unequal outer letters, so the count is 3.
There are three occurrences of a, two occurrences of aa, and one occurrence of aaa. They overlap and repeat the same text, but each start/end pair counts separately: 3 + 2 + 1 = 6.
The only non-empty substring is z itself. Its odd center adds one, and the gap after it is already outside the string.
Four single-character occurrences count, plus bb at indices 1..2 and abba at 0..3. Both longer palindromes share the middle gap, showing why even centers and every successful expansion must be counted.
Count occurrences, not distinct text: the three one-letter substrings in aaa count separately because their positions differ. A palindrome mirrors around a character for odd lengths or around a gap for even lengths. In Example 1, abc contributes only its three character centers; every neighboring gap fails immediately. Enumerating all endpoint pairs works, but growing each center shares the inner palindrome instead of repeatedly checking it.
Reveal Brute Force Check: intuition, complexity, and code
(i, i) and (i, i + 1) at every index. Count while bounds hold and characters match; stop at the first failure.z contributes exactly one odd palindrome and no even palindrome.500500 at the length limit 1000.abc contribute exactly n single-character occurrences.abba can contribute multiple palindromes (bb and abba); counting only character centers misses both.aaa contains six occurrences, even though there are only three distinct palindrome texts.bb in abba.When each valid interval has a unique center, enumerate centers and grow by one layer at a time. A preserved inner invariant replaces repeated full checks; counting every successful radius counts occurrences, while retaining only the largest radius solves a different objective.