Given a string str, the task is to find the number of odd length palindromic sub-sequences around of str with str[i] as centre i.e. every index will be considered as the centre one by one.
Input: str = “xyzx”
Output: 1 2 2 1
For index 0: There is only a single sub-sequence possible i.e. “x”
For index 1: Two sub-sequences are possible i.e. “y” and “xyx”
For index 2: “z” and “xzx”
For index 3: “x”
Input: str = “aaaa”
Output: 1 3 3 1
Approach: We will use dynamic programming to solve this problem. Let’s denote length of the sting str be N. Now, Let dp[i][j] denote the number of palindromic sub-sequences from 0 to i – 1 and number of palindromic sub-sequences from j to N – 1.
Let len be the distance between i and j. For each length len, we will fix our i and j, and check whether characters str[i] and str[j] are equal or not. Then according to it, we will make our dp transitions.
If str[i] != str[j] then dp[i][j] = dp[i – 1][j] + dp[i][j + 1] – dp[i – 1][j + 1]
If str[i] == str[j] then dp[i][j] = dp[i – 1][j] + dp[i][j + 1]
If i == 0 and j == n – 1 then dp[i][j] = 2 if str[i] == str[j] else dp[i][j] = 1.
Below is the implementation of the above approach:
1 3 4 3 1
- Number of balanced bracket subsequence of length 2 and 4
- Maximum length subsequence such that adjacent elements in the subsequence have a common factor
- Minimum length of the sub-string whose characters can be used to form a palindrome of length K
- Length of longest Palindromic Subsequence of even length with no two adjacent characters same
- Longest palindrome subsequence with O(n) space
- Nth Even length Palindrome
- Sum of first K even-length Palindrome numbers
- Length of the longest substring that do not contain any palindrome
- Maximum Sum Subsequence of length k
- Repeated subsequence of length 2 or more
- Subsequence X of length K such that gcd(X, X) + (X, X) + ... is maximized
- Maximum even length sub-string that is permutation of a palindrome
- Binary String of given length that without a palindrome of size 3
- Count subsequence of length three in a given string
- Length of Longest Balanced Subsequence
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.