内容中心

2026年质量好的北京断桥铝门窗厂家口碑推荐-实德门窗集美家居(北苑店)

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:

  1. DP Table Definition: Let dp[i][j] be True if the substring from index i to j (inclusive) is a palindrome, otherwise False.

  2. Base Cases:

    • All substrings of length 1 are palindromes, so dp[i][i] = True for all i.
    • Substrings of length 2 are palindromes if both characters are the same: dp[i][i+1] = (S[i] == S[i+1]).
  3. 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 substring S[i+1..j-1] is also a palindrome: dp[i][j] = (S[i] == S[j]) and dp[i+1][j-1].
  4. 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.

实德门窗集美家居(北苑店)



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?