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 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.
- Number of palindromic subsequences of length k where k <= 3
- Nth Even length Palindrome
- Minimum insertions to form a palindrome with permutations allowed
- Paper Cut into Minimum Number of Squares | Set 2
- Check if a binary string has a 0 between 1s or not | Set 2 (Regular Expression Approach)
- Lexicographically smallest rotated sequence | Set 2
- Find maximum possible stolen value from houses
- Number of n-digits non-decreasing integers
- Minimum steps to delete a string after repeated deletion of palindrome substrings
- Minimum number of deletions to make a string palindrome
- Count All Palindrome Sub-Strings in a String | Set 1
- Count All Palindromic Subsequence in a given String
- Count number of paths with at-most k turns
- Shortest Common Supersequence
- Longest Palindromic Substring | Set 1
Improved By : vt_m