In: Computer Science
removeRep(“yyzzza”) à “yza”
removeRep(“aabbbccd”) à “abcd”
removeRep(“122333”) à “123”
Here is the complete code filled with comments to help understand all the lines.
The code is in c++ but can also be applied to java and other languages as the logic remains the same.
//These are the required header file
#include <iostream>
#include <string>
using namespace std;
string removeRep(string str)
{
//first we take the length of the string
int len = str.size();
//if length is less 2 we can simple return the string as it is
if (len <= 1)
return str;
int j = 0;
//we have kept the variable j to increase ONLY when we find a new unique element, thus there are no duplicates
for (int i = 1; i < len; i++)
{
if (str[i] != str[j])
{
str[++j] = str[i];
}
}
j++;
//at last resize the string to the required length ie j
str.resize(j);
return str;
}
int main()
{
cout << removeRep("aazzzpp") << "\n";
cout << removeRep("aabbbccccddd") << "\n";
cout << removeRep("abcd") << "\n";
cout << removeRep("bppppaz") << "\n";
return 0;
}
Here is the output for the above code