To solve this problem, we need to find the number of distinct non-empty palindromic substrings in a given string. A palindromic substring reads the same forwards and backwards, and we need to count each unique substring only once.
Approach
The key insight here is that every palindrome has a center. For odd-length palindromes, the center is a single character, and for even-length palindromes, the center is between two consecutive characters. We can expand around each center to find all palindromic substrings and store them in a set to avoid duplicates.
- Odd-length Palindromes: For each character as the center, expand outwards as long as the characters on both sides are the same.
- Even-length Palindromes: For each pair of consecutive characters as the center, expand outwards similarly.
- Distinct Substrings: Use a set to store all palindromic substrings, ensuring each substring is counted only once.
Solution Code
def count_distinct_palindromic_substrings(s):
palindromes = set()
n = len(s)
# Check for odd-length palindromes
for i in range(n):
l, r = i, i
while l >= 0 and r < n and s[l] == s[r]:
palindromes.add(s[l:r+1])
l -= 1
r += 1
# Check for even-length palindromes
for i in range(n-1):
l, r = i, i+1
while l >= 0 and r < n and s[l] == s[r]:
palindromes.add(s[l:r+1])
l -= 1
r += 1
return len(palindromes)
# Example usage:
# print(count_distinct_palindromic_substrings("abba")) # Output: 4
# print(count_distinct_palindromic_substrings("aaa")) # Output: 3
# print(count_distinct_palindromic_substrings("abc")) # Output: 3
Explanation
- Odd-length Palindromes: We start with each character as the center and expand left and right. For each valid expansion (same characters on both sides), we add the substring to the set.
- Even-length Palindromes: We start with each pair of consecutive characters as the center and expand similarly, adding valid substrings to the set.
- Set for Uniqueness: The set automatically handles duplicates, so we only count each distinct palindromic substring once.
This approach efficiently finds all distinct palindromic substrings with a time complexity of O(n²) (since each center expansion takes O(n) time and there are O(n) centers), which is optimal for most practical purposes. The space complexity is O(n²) in the worst case (all substrings are palindromic), but this is manageable for typical input sizes.
The final result is the size of the set, which gives the number of distinct palindromic substrings.
Answer: The function count_distinct_palindromic_substrings returns the number of distinct palindromic substrings. For example, if the input string is "abba", the answer is 4. If the input is "aaa", the answer is 3, etc. The code can be used directly to get the desired result.

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