内容中心

2026年知名的泸州玻璃钢防腐工程厂家选择推荐-泸州欧亚达防腐设备有限公司

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:

  1. Odd-length: The center is a single character (e.g., "aba" has center at index 1).
  2. Even-length: The center is between two characters (e.g., "abba" has center between indices 1 and 2).

The steps are:

  1. 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.
  2. For each pair of consecutive characters, consider them as the center of an even-length palindrome and expand outwards similarly.
  3. 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 with l = i and r = 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 with l = i and r = 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 n characters (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.

泸州欧亚达防腐设备有限公司



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

在线客服

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