Given a string S, The task is to remove all the consecutive duplicate characters of the string and return the resultant string.
Note: that this problem is different from Recursively remove all adjacent duplicates. Here we keep one character and remove all subsequent same characters.
Examples:
Input: S= “aaaaabbbbbb”
Output: abInput: S = “geeksforgeeks”
Output: geksforgeksInput: S = “aabccba”
Output: abcba
Remove all consecutive duplicates from the string using recursion:
Approach:
If the string is not empty compare the adjacent characters of the string. If they are the same then shift the characters one by one to the left. Call recursion on string S otherwise, call recursion from S+1 string.
Follow the below steps to implement the idea:
- If the string is empty, return.
- Else compare the adjacent characters of the string. If they are the same then shift the characters one by one to the left. Call recursion on string S
- If they are not same then call recursion from S+1 string.
Illustration:
The recursion tree for the string S = aabcca is shown below.
aabcca S = aabcca
/
abcca S = abcca
/
bcca S = abcca
/
cca S = abcca
/
ca S = abca
/
a S = abca [Output String]
/
empty string
Below is the implementation of the above approach:
C++
#include
using
namespace
std;
void
removeDuplicates[
char
* S]
{
if
[S[0] ==
'\0'
]
return
;
if
[S[0] == S[1]] {
int
i = 0;
while
[S[i] !=
'\0'
] {
S[i] = S[i + 1];
i++;
}
removeDuplicates[S];
}
removeDuplicates[S + 1];
}
int
main[]
{
char
S1[] =
"geeksforgeeks"
;
removeDuplicates[S1];
cout