To solve the problem of counting the number of palindromic substrings in a given string, we can use an efficient approach that expands around potential centers of palindromes. This method avoids the brute-force O(n³) complexity and instead achieves O(n²) time complexity, which is optimal for this problem.
Approach
A palindrome can be of two types:
- Odd-length: The center is a single character (e.g., "aba" has center at index 1).
- Even-length: The center is between two characters (e.g., "abba" has center between indices 1 and 2).
The steps are:
- For each character in the string, consider it as the center of an odd-length palindrome and expand outwards as long as the characters on both sides are equal.
- For each pair of consecutive characters, consider them as the center of an even-length palindrome and expand outwards similarly.
- Count all valid palindromic substrings found during these expansions.
Solution Code
def count_palindromic_substrings(s):
count = 0
n = len(s)
for i in range(n):
# Check for odd-length palindromes (center at i)
l, r = i, i
while l >= 0 and r < n and s[l] == s[r]:
count += 1
l -= 1
r += 1
# Check for even-length palindromes (center between i and i+1)
l, r = i, i + 1
while l >= 0 and r < n and s[l] == s[r]:
count += 1
l -= 1
r += 1
return count
Explanation
- Odd-length palindromes: For each index
i, we start withl = iandr = i(same character). We increment the count and expand left (l -=1) and right (r +=1) as long as the characters at these positions are equal. - Even-length palindromes: For each index
i, we start withl = iandr = i+1(consecutive characters). We increment the count and expand similarly if the characters are equal. - Efficiency: Each expansion step runs in O(n) time in the worst case, but since we do this for each of the
ncharacters (and their consecutive pairs), the overall time complexity is O(n²), which is efficient for most problem constraints.
This approach effectively counts all palindromic substrings by leveraging the symmetry of palindromes, making it both optimal and easy to implement. For example:
- For
s = "aaa", the count is 6 (3 single characters, 2 pairs, and 1 triplet). - For
s = "abc", the count is 3 (only single characters are palindromic).
This solution is correct and handles all edge cases, including empty strings (returns 0) and single-character strings (returns 1).
Final Answer
The function `count_palindromic_substrings` returns the number of palindromic substrings in the input string. For example, if the input is "aaa", the answer is 6.

作者声明:本文包含人工智能生成内容。