Palindromic Substrings
Problem Statement
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.
Constraints:
- 1 <= s.length <= 1000
- s consists of lowercase English letters
Input Format:
- A string s
Output Format:
- An integer representing the number of palindromic substrings
Examples:
Example 1:
Input:
s = "abc"
Output:
3
Explanation:
Three palindromic strings: "a", "b", "c".
Example 2:
Input:
s = "aaa"
Output:
6
Explanation:
Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Solutions
Expand Around Center
Check each position as a potential center and count all palindromes.
Dynamic Programming
Use a 2D table to track whether each substring is a palindrome.
Algorithm Walkthrough
Example input:
Step-by-step execution:
- Input: s = "aaa"
- Initialize count = 0
- Iterate through each position:
- i = 0, character 'a':
- Odd center: expand(0,0):
- Palindrome 'a', count = 1
- Even center: expand(0,1):
- Palindrome 'aa', count = 2
- i = 1, character 'a':
- Odd center: expand(1,1):
- Palindrome 'a', count = 3
- Even center: expand(1,2):
- Palindrome 'aa', count = 4
- i = 2, character 'a':
- Odd center: expand(2,2):
- Palindrome 'a', count = 5
- Even center: expand(2,3): Out of bounds
- The entire string "aaa" is also a palindrome, found when expanding from position 1
- Total count = 6
Hints
Hint 1
Hint 2
Hint 3
Video Tutorial
Video tutorials can be a great way to understand algorithms visually
Visualization
Visualize the expansion process around each center position and count all the palindromic substrings found.
Key visualization elements:
- current center
- expanding boundaries
- found palindromes
Implementation Notes
Both approaches have the same time complexity, but the 'Expand Around Center' approach is generally preferred due to its simplicity and O(1) space complexity, compared to the O(n²) space complexity of the dynamic programming approach.