Introduction
The programs involving strings serve as crucial interview questions in many companies to date. In this tutorial, we will discuss the concept of the C++ programming language using which we will code how to recursively remove all adjacent duplicate characters in a string. We will take an input for which the program will return the desired output. For example, moon. We have to remove all the adjacent duplicate characters till there are none. The output of the above input will be mn. Here are a few more examples.
webber - wr (First, both the b's are removed, then both the e's)
reeree - empty string(First two e's are removed, then the last two e's and both the r's)
Approach
Suppose we take a string s of length n. We will start from the leftmost character and remove duplicates at the leftmost corner, if any, ensuring the first character is different from its adjacent. Repeat the same for the remaining string of length n-1. Let the reduced string be s2. There are the following cases possible.
- The first character of s2 matches s. Then, remove that character from s2.
- The s2 string becomes empty since the last removed character is the same as the first character of s. Then the resultant output will be an empty string.
-
If the above-mentioned cases do not work, append the first character of s at the beginning of s2.
Then, return s2 as the output.
Time Complexity: O(n)
Also read, Application of Oops