This is a question in the book "Cracking The Coding Interview".
Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not.
Follow Up
Write the test cases for this method. The four test cases are
- String does not contain any duplicates, e.g.: abcd
- String contains all duplicates, e.g.: aaaa
- Null string
- String with all continuous duplicates, e.g.: aaabbb
I want to optimise this code and whether I can use some other function from STL.
#include <iostream>
#include <string>
#include <algorithm>
std::string & removeDuplicate(std::string& str)
{
int length = str.length();
for(unsigned int i = 0; i < length; i++)
{
char currChar = str[i]; //holds current character
for(unsigned int j = i+1; j < length; j++)
{
if(currChar == str[j])
str.erase (std::remove(str.begin()+j, str.end(), str[j]), str.end());
}
}
return str;
}
int main()
{
std::string str;
std::cout << "Enter string \n";
std::getline(std::cin, str);
str = removeDuplicate(str);
std::cout <<"New String is " << str << "\n";
}
j
loop and if statement completely and it will still work. \$\endgroup\$std::unique
. Just take a look at this article from the reference, there are possible implementations described: en.cppreference.com/w/cpp/algorithm/unique \$\endgroup\$