![]() |
VOOZH | about |
Given a string str, the task is to find the number of odd length palindromic sub-sequences around of str with str[i] as center i.e. every index will be considered as the center one by one.
Examples:
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 string 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]
Base case:
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
Time Complexity: O(n2)
Auxiliary Space: O(n2), where n is the length of the given string.