Given a string, the task is to count all palindrome substring in a given string. Length of palindrome substring is greater then or equal to 2.
Input : str = "abaab" Output: 3 Explanation : All palindrome substring are : "aba" , "aa" , "baab" Input : str = "abbaeae" Output: 4 Explanation : All palindrome substring are : "bb" , "abba" ,"aea","eae"
We have discussed a similar problem below.
Find all distinct palindromic sub-strings of a given string
The above problem can be recursively defined.
Initial Values : i = 0, j = n-1; Given string 'str' CountPS(i, j) // If length of string is 2 then we // check both character are same or not If (j == i+1) return str[i] == str[j] Else If str[i..j] is PALINDROME // increment count by 1 and check for // rest palindromic substring (i, j-1), (i+1, j) // remove common palindrome substring (i+1, j-1) return countPS(i+1, j) + countPS(i, j-1) + 1 - countPS(i+1, j-1); Else // if NOT PALINDROME // We check for rest palindromic substrings (i, j-1) // and (i+1, j) // remove common palindrome substring (i+1 , j-1) return countPS(i+1, j) + countPS(i, j-1) - countPS(i+1 , j-1);
If we draw recursion tree of above recursive solution, we can observe overlapping Subprolems. Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic Programming. Below is Dynamic Programming based solution.
Time complexity: O(n2)
Auxiliary Space: O(n2)
This article is contributed by Nishant_Singh(Pintu). 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Minimum steps to delete a string after repeated deletion of palindrome substrings
- Count of substrings of a binary string containing K ones
- Given a binary string, count number of substrings that start and end with 1.
- Count the number of vowels occurring in all the substrings of given string
- Count of distinct substrings of a string using Suffix Array
- Count of distinct substrings of a string using Suffix Trie
- Count All Palindrome Sub-Strings in a String | Set 2
- Count all palindrome which is square of a palindrome
- Count substrings with same first and last characters
- Count of total anagram substrings
- Number of substrings with count of each character as k
- Count Substrings with equal number of 0s, 1s and 2s
- Count number of substrings with exactly k distinct characters
- Count number of substrings with numeric value greater than X
- Count of Palindromic substrings in an Index range
Improved By : shrikanth13