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 firstname.lastname@example.org. 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.
- Number of palindromic subsequences of length k where k <= 3
- Count All Palindrome Sub-Strings in a String | Set 2
- Count of Palindromic substrings in an Index range
- Minimum characters to be added at front to make string palindrome
- Maximum subsequence sum such that no three are consecutive
- Check for Palindrome after every character replacement Query
- Count All Palindromic Subsequence in a given String
- Given a string, print all possible palindromic partitions
- Find all distinct palindromic sub-strings of a given string
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1
- Longest Palindromic Substring | Set 2
- Longest Palindromic Substring | Set 1
- Palindrome Partitioning | DP-17
- Longest Palindromic Subsequence | DP-12
- Largest Sum Contiguous Subarray