![]() |
VOOZH | about |
Given string str. The task is to find the longest subsequence of str such that all the characters adjacent to each other in the subsequence are different.
Examples:
Input: str = "ababa"
Output: 5
Explanation:
"ababa" is the subsequence satisfying the conditionInput: str = "xxxxy"
Output: 2
Explanation:
"xy" is the subsequence satisfying the condition
Method 1: Greedy Approach
It can be observed that choosing the first character which is not similar to the previously chosen character given the longest subsequence of the given string with different adjacent characters.
The idea is to keep track of previously picked characters while iterating through the string, and if the current character is different from the previous character, then count the current character to find the longest subsequence.
Implementation:
5
Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Method 2: Dynamic Programming
Let dp[pos][prev] be the length of longest subsequence till index pos such that alphabet prev was picked previously.a dp[pos][prev] = max(1 + function(pos+1, s[pos] - 'a' + 1, s), function(pos+1, prev, s));
Below is the implementation of the above approach:
5
Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(26*N) where N is the length of the given string.
Approach 2: Using DP Tabulation method ( Iterative approach )
The approach to solving this problem is the same but DP tabulation(bottom-up) method is better then Dp + memorization(top-down) because memorization method needs extra stack space of recursion calls.
Steps to solve this problem:
Implementation:
5
Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(N) where N is the length of the given string.