Given a string S. The task is to count the non-overlapping pairs of palindromic sub-strings S1 and S2 such that the strings should be S1[L1…R1] and S2[L2…R2] where 0 ≤ L1 ≤ R1 < L2 ≤ R2 < N. The task is to count the number of pairs of the non-overlapping palindromic sub-strings.
Input: s = “aaa”
All possible pairs are (s, s), (s, s),
(s, s[1, 2]), (s, s) and (s[0, 1], s)
Input: s = “abacaba”
Approach: We can use Dynamic Programming to solve the above problem. We can initially create the DP table which stores if substring[i….j] is palindrome or not. We maintain a boolean dp[n][n] that is filled in a bottom-up manner. The value of dp[i][j] is true if the substring is a palindrome, otherwise false. To calculate dp[i][j], we first check the value of dp[i+1][j-1], if the value is true and s[i] is same as s[j], then we make dp[i][j] true. Otherwise, the value of dp[i][j] is made false. The following steps can be followed thereafter to get the number of pairs.
- Create a left array, where left[i] stores the count of the number of palindromes to the left on the index i including i.
- Create a right array, where right[i] stores the count of the number of palindromes to the right on the index i including i.
- Iterate from 0 to length-1 and add left[i]*right[i+1]. The summation of it for every index will be the required number of pairs.
Below is the implementation of the above approach:
- Count of Palindromic substrings in an Index range
- Count all Prime Length Palindromic Substrings
- Rearrange the string to maximize the number of palindromic substrings
- Find the count of palindromic sub-string of a string in its sorted form
- Count All Palindromic Subsequence in a given String
- Count palindromic characteristics of a String
- Count of substrings of a binary string containing K ones
- Count number of substrings of a string consisting of same characters
- Count of distinct substrings of a string using Suffix Array
- 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 Trie
- Queries to find the count of vowels in the substrings of the given string
- Minimum cuts required to convert a palindromic string to a different palindromic string
- Make palindromic string non-palindromic by rearranging its letters
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.