Problem Description
Given a string s, count and return the number of palindromic substrings found in s. A palindrome reads the same backward as forward, and every single character is considered a palindrome by itself.
Key Insights
- Every individual character is a palindrome.
- Palindromes can be expanded from a center point; centers can be single characters (odd length) or between two characters (even length).
- The "expand around center" technique efficiently counts palindromes in O(n^2) time.
- Dynamic programming could also be used but requires extra space and is more complex to implement.
Space and Time Complexity
Time Complexity: O(n^2) where n is the length of the string. Space Complexity: O(1) if using the expand-around-center method (ignoring recursion/stack overhead).
Solution
The solution employs the expand-around-center approach:
- Iterate over each index of the string considering it as the center of a palindrome.
- For each center, expand in both directions (left and right) as long as the characters are the same and within bounds.
- Count every valid palindrome found during the expansion.
- Repeat for both odd-length centers (a single index) and even-length centers (between two indices).
This method efficiently checks all potential palindromic substrings without extra space for dynamic programming tables.