Find all distinct palindromic sub-strings of a given String in Python

Suppose we have a string with lowercase ASCII characters, we have to find all distinct continuous palindromic substrings of it.

So, if the input is like "bddaaa", then the output will be [a, aa, aaa, b, d, dd]

To solve this, we will follow these steps −

  • m := a new map
  • n := size of s
  • matrix := make two rows of n number of 0s
  • s := "@" concatenate s concatenate "#"
  • for j in range 0 to 1, do
    • temp := 0
    • matrix[j, 0] := 0
    • i := 1
    • while i
    • while s[i - temp - 1] is same as s[i + j + temp], do
      • temp := temp + 1
    • matrix[j, i] := temp
    • k := 1
    • while (matrix[j, i - k] is not same as temp - k) and k
    • matrix[j,i+k] := minimum of matrix[j, i-k]
    • k := k + 1
  • temp := maximum of temp - k, 0
  • i := i + k
  • s := s from index 1 to end
  • m[s[0]] := 1
  • for i in range 1 to n, do
    • for j in range 0 to 1, do
      • for temp in range, do
        • m[substring of s from (i - temp - 1) to (i - temp - 1 + 2 * temp + j)] = 1

    • m[s[i]] := 1
  • for each i in m, do
    • display i
  • Example

    Let us see the following implementation to get better understanding −

     Live Demo

    def find_substr(s):
       m = dict()
       n = len(s)
       matrix = [[0 for x in range(n+1)] for x in range(2)]
       s = "@" + s + "#"
       for j in range(2):
          temp = 0
          matrix[j][0] = 0
          i = 1
          while i 

    Input

    bddaaa

    Output

    a
    aa
    b
    aaa
    d
    dd
    Updated on: 2020-08-28T08:55:03+05:30

    458 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements