用 Python 编写程序来计算回文子串的数量

pythonserver side programmingprogramming更新于 2026/2/2 3:56:17

假设我们有一个字符串 s,我们必须找出 s 中回文子串的数量。

因此,如果输入为 s = "level",则输出将为 7,因为回文子串为:["l","e","v","e","l","eve","level"]

为了解决这个问题,我们将遵循以下步骤 −

  • 定义一个函数 check_palindrome()。这将采用字符串、左、右
  • ans := 0
  • 而左 >= 0 且右 < s 的大小,执行
    • 如果 s[left] 与 s[right] 相同,则
      • ans := ans + 1
      • left := left - 1
      • right := right + 1
    • 否则,
      • 返回 ans
  • 返回 ans
  • 从主方法,执行以下操作 −
  • ans := 0
  • 对于 0 到 s 的大小范围内的 char_index,执行
    • ans := ans + check_palindrome(s, char_index - 1, char_index + 1)
    • ans := ans + check_palindrome(s, char_index, char_index + 1)
  • 返回 (ans) + s 的大小

让我们看看下面的实现以便更好地理解 −

示例

class Solution:
   def solve(self, s):
      def check_palindrome(string, left, right):
         ans = 0
         while left >= 0 and right < len(s):
            if s[left] == s[right]:
               ans += 1
               left -= 1
               right += 1
            else:
               return ans
         return ans
      ans = 0
      for char_index in range(len(s)):
         ans += check_palindrome(s, char_index - 1, char_index + 1)
         ans += check_palindrome(s, char_index, char_index + 1)
      return (ans) + len(s)
ob = Solution()
print(ob.solve("level"))

输入

"level"

输出

7

相关文章


有用资源