To solve this problem, we need to count the number of distinct palindromic substrings of length at least 2 in a given string. A palindromic substring reads the same forwards and backwards.
Approach
The approach uses dynamic programming (DP) to efficiently determine if a substring is a palindrome. Here's the detailed breakdown:
-
DP Table Definition: Let
dp[i][j]beTrueif the substring from indexitoj(inclusive) is a palindrome, otherwiseFalse. -
Base Cases:
- All substrings of length 1 are palindromes, so
dp[i][i] = Truefor alli. - Substrings of length 2 are palindromes if both characters are the same:
dp[i][i+1] = (S[i] == S[i+1]).
- All substrings of length 1 are palindromes, so
-
DP Transition:
- For substrings of length greater than 2, a substring
S[i..j]is a palindrome if the first and last characters are the same, and the substringS[i+1..j-1]is also a palindrome:dp[i][j] = (S[i] == S[j]) and dp[i+1][j-1].
- For substrings of length greater than 2, a substring
-
Count Palindromic Substrings: We count all substrings of length >=2 that are palindromes using the DP table.
Solution Code
s = input().strip()
n = len(s)
if n < 2:
print(0)
else:
count = 0
dp = [[False] * n for _ in range(n)]
# Base case: all single characters are palindromes
for i in range(n):
dp[i][i] = True
# Check substrings of length 2
for i in range(n - 1):
if s[i] == s[i + 1]:
dp[i][i + 1] = True
count += 1
# Check substrings of length >=3
for length in range(3, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if s[i] == s[j] and dp[i + 1][j - 1]:
dp[i][j] = True
count += 1
print(count)
Explanation
- Base Case Handling: We first mark all single characters as palindromes since they trivially satisfy the condition.
- Length 2 Substrings: We check each pair of consecutive characters to see if they form a palindrome.
- Longer Substrings: For each possible length starting from 3 up to the length of the string, we check if the substring is a palindrome by verifying the first and last characters and the palindrome status of the inner substring.
- Count: We increment the count for each valid palindromic substring of length >=2.
This approach efficiently computes the result with a time complexity of O(n²) and space complexity of O(n²), which is feasible for most practical input sizes. The DP table helps avoid redundant calculations and ensures we correctly identify all palindromic substrings.

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