To solve this problem, we need to count the number of palindromic substrings in a given string. A palindromic substring reads the same forwards and backwards. The efficient approach to solve this problem involves expanding around potential centers of palindromes, which can be either a single character (for odd-length palindromes) or between two characters (for even-length palindromes).
Approach
- Expand Around Centers:
- For each character in the string, consider it as the center of an odd-length palindrome. Expand outwards as long as the characters on both sides are the same, counting valid palindromic substrings.
- For each pair of consecutive characters, consider them as the center of an even-length palindrome. Expand outwards similarly, counting valid palindromic substrings.
- Count Valid Substrings: Sum the counts from both odd and even length palindromes to get the total number of palindromic substrings.
Solution Code
def count_palindromic_substrings(s):
n = len(s)
count = 0
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
# Example usage:
# print(count_palindromic_substrings("aaa")) # Output:6
# print(count_palindromic_substrings("abc")) # Output:3
# print(count_palindromic_substrings("abba")) # Output:6
Explanation
- Odd-Length Palindromes: For each character at index
i, we start withl = iandr = i(same position). We expand left (l--) and right (r++) as long ass[l] == s[r]and the indices are within bounds. Each valid expansion adds a palindromic substring to the count. - Even-Length Palindromes: For each pair of consecutive characters at indices
iandi+1, we start withl = iandr = i+1. We expand similarly, checking if the characters are the same and within bounds, adding valid substrings to the count. - Time Complexity: The algorithm runs in O(N²) time, where N is the length of the string. This is because for each of the N characters, we expand up to N times in the worst case (e.g., a string of all the same characters).
- Space Complexity: The algorithm uses O(1) additional space, as it only uses a few variables to track the current expansion and count.
This approach efficiently counts all palindromic substrings by leveraging the symmetry property of palindromes, making it suitable for most practical input sizes.


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