Find the count of palindromic sub-string of a string in its sorted form in Python


Suppose we have a string of lowercase characters (all are ASCII characters), we have to find all distinct continuous palindromic sub-strings of the given string.

So, if the input is like "level", then the output will be 7 as there are seven substrings ['level', 'eve', 'l', 'e', 'v', 'e', 'l'].

To solve this, we will follow these steps −

  • N := 26

  • n := length of str

  • sum := 0

  • my_map := a list of size N and fill with 0

  • for i in range 0 to n, do

    • my_map[ASCII of (str[i]) - ASCII of ('a') ] := my_map[ASCII of (str[i]) - ASCII of ('a') ] + 1

  • for i in range 0 to N, do

    • if my_map[i] is non-zero, then

      • sum := sum +(my_map[i] *(my_map[i] + 1) / 2)

  • return sum

Example 

Let us see the following implementation to get better understanding −

 Live Demo

N = 26
def all_palindrome_substr_count(str):
   n = len (str)
   sum = 0
   my_map = [0] * N
   for i in range(n):
      my_map[ord(str[i]) - ord('a')] += 1
  for i in range(N) :
      if (my_map[i]):
         sum += (my_map[i] * (my_map[i] + 1) // 2)
   return sum
str = "level"
print (all_palindrome_substr_count(str))

Input

"level"

Output

7

Updated on: 19-Aug-2020

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements