Find all palindromic sub-strings of a given string - Set 2 in Python


Suppose we have a string; we have to find all the palindromic sub-strings from that string. Here aa and aa are considered as two sub-strings, not one.

So, if the input is like redivider, then the output will be ['r', 'e', 'd', 'i', 'v', 'ivi', 'divid', 'edivide', 'redivider', 'i', 'd', 'e', 'r']

To solve this, we will follow these steps −

  • v := a new list
  • pos := 0.0
  • while pos < size of s, do
    • rad := pos - (pos as integer)
    • while (pos + rad) < size of s and (pos - rad) >= 0 and (s[integer of (pos - rad)] is same as s[integer of (pos + rad)]), do
      • insert s[from index integer of (pos - rad) to integer of (pos + rad + 1)] at the end of v
      • rad := rad + 1
    • pos := pos + 0.5
  • return v

Example Code

Let us see the following implementation to get better understanding −

 Live Demo

def get_all_pal_sub(s):
   v = []
   pos = 0.0
   while pos < len(s):
      rad = pos - int(pos)
      while ((pos + rad) < len(s) and (pos - rad) >= 0 and (s[int(pos - rad)] == s[int(pos + rad)])):
         v.append(s[int(pos - rad): int(pos + rad + 1)])
         rad += 1
      pos += 0.5
   return v
v = get_all_pal_sub("redivider")
print(len(v))
print(v)

Input

"redivider"

Output

13 ['r', 'e', 'd', 'i', 'v', 'ivi', 'divid', 'edivide', 'redivider', 'i', 'd', 'e', 'r']

Updated on: 28-Aug-2020

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements