Given a string str consisting of lowercase English alphabets, the task is to find the total number of palindromic sub-strings present in the sorted form of str.
Input: str = “acbbd”
All palindromic sub-string in it’s sorted form (“abbcd”) are “a”, “b”, “b”, “bb”, “c” and “d”.
Input: str = “abbabdbd”
Naive approach: One way is to sort the given string and then count the total number of sub-strings present which are palindromes. For finding number of palindromic sub-strings this approach can be used which has time complexity of O(n^2).
Optimized approach: An efficient way is to count the frequency of each character and then for each frequency total number of palindromes will (n*(n+1))/2 as all the palindromic sub-strings of a sorted string will consist of the same character.
For example, palindromic sub-string for the string “aabbbcd” will be “a”, “aa”, …, “bbb”, “c”, … etc. Time complexity for this approach will be O(n).
- Create a hash table for storing the frequencies of each character of the string str.
- Traverse the hash table and for each non-zero frequency add (hash[i] * (hash[i]+1)) / 2 to the sum.
- Print the sum in the end.
Below is the implementation of the above approach:
- Longest Palindromic Substring using Palindromic Tree | Set 3
- Find if a given string can be represented from a substring by iterating the substring “n” times
- Count All Palindromic Subsequence in a given String
- Count palindromic characteristics of a String
- Count pairs of non-overlapping palindromic sub-strings of the given string
- Minimum cuts required to convert a palindromic string to a different palindromic string
- Find a palindromic string B such that given String A is a subsequense of B
- Find all palindromic sub-strings of a given string | Set 2
- Find length of longest subsequence of one string which is substring of another string
- Decode a string recursively encoded as count followed by substring
- Find all distinct palindromic sub-strings of a given string
- Find the lexicographically largest palindromic Subsequence of a String
- Make palindromic string non-palindromic by rearranging its letters
- Longest Palindromic Substring | Set 2
- Longest Palindromic Substring | Set 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.