Given a string str of small alphabetic characters other than this we will be given many substrings of this string in form of index tuples. We need to find out the count of the palindromic substrings in given substring range.
Input : String str = "xyaabax" Range1 = (3, 5) Range2 = (2, 3) Output : 4 3 For Range1, substring is "aba" Count of palindromic substring in "aba" is four : "a", "b", "aba", "a" For Range2, substring is "aa" Count of palindromic substring in "aa" is 3 : "a", "a", "aa"
Prerequisite : Count All Palindrome Sub-Strings in a String
We can solve this problem using dynamic programming. First we will make a 2D array isPalin, isPalin[i][j] will be 1 if string(i..j) is a palindrome otherwise it will be 0. After constructing isPalin we will construct another 2D array dp, dp[i][j] will tell the count of palindromic substring in string(i..j)
Now we can write the relation among isPalin and dp values as shown below,
// isPalin[i][j] will be 1 if ith and jth characters // are equal and mid substring str(i+1..j-1) is also // a palindrome isPalin[i][j] = (str[i] == str[j]) and (isPalin[i + 1][j – 1]) // Similar to set theory we can write the relation among // dp values as, // dp[i][j] will be addition of number of palindromes from // i to j-1 and i+1 to j subtracting palindromes from i+1 // to j-1 because they are counted twice once in dp[i][j-1] // and then in dp[i + 1][j] plus 1 if str(i..j) is also a // palindrome dp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1] + isPalin[i][j];
Total time complexity of solution will be O(length ^ 2) for constructing dp array then O(1) per query.
This article is contributed by Utkarsh Trivedi. 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.
- Count all Prime Length Palindromic Substrings
- Rearrange the string to maximize the number of palindromic substrings
- Sum of all odd length palindromic numbers within the range [L, R]
- Count substrings that contain all vowels | SET 2
- Count substrings with same first and last characters
- Count all substrings having character K
- Count All Palindromic Subsequence in a given String
- Count palindromic characteristics of a String
- Number of substrings with count of each character as k
- Count of substrings of a binary string containing K ones
- Count Substrings with equal number of 0s, 1s and 2s
- Count of total anagram substrings
- Count of substrings which contains a given character K times
- Count number of substrings with exactly k distinct characters
- Count substrings with each character occurring at most k times