The question is asking to remove duplicates from the string, I came up with a solution to remove duplicates but for that, I sorted the string. So I wanted to know is there a way of removing duplicates from a string without sorting the string.
Test Cases :
"allcbcd" -> "alcbd"
My Code (the one in which string has to be sorted) :
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string removeDup(string s)
{
if (s.length() == 0)
{
return "";
}
sort(s.begin(), s.end());
char ch = s[0];
string ans = removeDup(s.substr(1));
if (ch == ans[0])
{
return ans;
}
return (ch ans);
}
int main()
{
cout << removeDup("allcbbcd") << endl;
return 0;
}
CodePudding user response:
Here is one way to do it without sorting (or using a recursive loop):
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string removeDup(string s)
{
string::size_type index = 0;
string::iterator end = s.end();
while (index < s.size()) {
end = remove(s.begin() index 1, end, s[index]);
index;
}
s.erase(end, s.end());
return s;
}
int main()
{
cout << removeDup("allcbbcd") << endl;
return 0;
}
CodePudding user response:
I goofed. The solution I provided was for python. But here is a c solution where users provide a few different stl methods.