I am trying to write optimal code (good runtime efficiency) for removing duplicate words in a sentence.
For example the input string Jack Juliet Juliet Jill Jack Romeo Jack Jill
to the function should return Jack Juliet Jill Romeo
The following is my code :
std::string removeDuplicateWords(const std::string& str)
{
std::stringstream ss (str);
std::unordered_set<std::string> string_history;
std::string current_string, output_string;
ss >> current_string;
string_history.insert(current_string);
output_string += current_string;
while(ss >> current_string) {
if(string_history.find(current_string) == string_history.end()) {
output_string += " " + current_string;
string_history.insert(current_string);
}
}
return output_string;
}
Aucun commentaire:
Enregistrer un commentaire