- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 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 −
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
Advertisements