Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 <= n, do
- 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 < temp, do
- matrix[j,i+k] := minimum of matrix[j, i-k]
- k := k + 1
- temp := maximum of temp - k, 0
- i := i + k
- while s[i - temp - 1] is same as s[i + j + temp], do
- 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
- for temp in range, do
- m[s[i]] := 1
- for j in range 0 to 1, do
- for each i in m, do
- display i
Example
Let us see the following implementation to get better understanding −
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 <= n:
while s[i - temp - 1] == s[i + j + temp]:
temp += 1
matrix[j][i] = temp
k = 1
while (matrix[j][i - k] != temp - k) and (k < temp):
matrix[j][i+k] = min(matrix[j][i-k], temp - k)
k += 1
temp = max(temp - k, 0)
i += k
s = s[1:len(s)-1]
m[s[0]] = 1
for i in range(1,n):
for j in range(2):
for temp in range(matrix[j][i],0,-1):
m[s[i - temp - 1 : i - temp - 1 + 2 * temp + j]] = 1
m[s[i]] = 1
for i in m:
print (i)
find_substr("bddaaa")
Input
bddaaa
Output
a aa b aaa d dd
Advertisements