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
Follow Up
Write the test cases for this method. The four test cases are
The four test cases are
1.String does not contain any duplicates, e.g.: abcd 2.String contains all duplicates, e.g.: aaaa 3.Null string 4.String with all continuous duplicates, e.g.: aaabbb
- 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";
}