Program to count number of palindromic substrings in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s, we have to find the number of palindromic substrings in s.

So, if the input is like s = "level", then the output will be 7, as the palindromic substrings are: ["l","e","v","e","l","eve","level"]

To solve this, we will follow these steps −

  • Define a function check_palindrome(). This will take string, left, right
  • ans := 0
  • while left >= 0 and right < size of s, do
    • if s[left] is same as s[right], then
      • ans := ans + 1
      • left := left - 1
      • right := right + 1
    • otherwise,
      • return ans
  • return ans
  • From the main method, do the following −
  • ans := 0
  • for char_index in range 0 to size of s, do
    • ans := ans + check_palindrome(s, char_index - 1, char_index + 1)
    • ans := ans + check_palindrome(s, char_index, char_index + 1)
  • return (ans) + size of s

Let us see the following implementation to get better understanding −

Example

 Live Demo

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"))

Input

"level"

Output

7
raja
Published on 19-Oct-2020 15:59:12
Advertisements