patterncppMinor
Find common characters
Viewed 0 times
characterscommonfind
Problem
Given two strings, find the common characters.
Is there better implementation for this problem?
Is there better implementation for this problem?
#include
#include
#include
std::string find_intersection(std::string & first, std::string & second)
{
std::sort(std::begin(first),std::end(first));
std::sort(std::begin(second), std::end(second));
int length = std::min(first.length(), second.length());
std::string result(length,' ');
std::set_intersection(std::begin(first),std::end(first),std::begin(second),std::end(second),std::begin(result));
result.shrink_to_fit();
return result;
}
int main()
{
std::string first="GermanTown";
std::string second="Georgia";
std::cout<<find_intersection(first,second)<<"\n";
return 0;
}Solution
For the same reasons as @DJanssens, I would like to compliment you for a simple and clean algorithm making proper use of the standard library. That may seem basic, but there are too many people ignoring the standard `
in the world, so I'm glad that you decided to use it. I only want to add two more things:
-
First, I don't think that shrink_to_fit will do what you expect it to do. When you construct result, you allocate memory and fill it with spaces, so result's size probably grew to. shrink_to_fit will get rid of the allocated but unused memory, but it won't get rid of the extra spaces that you allocated at construction.
-
What you can do is default-construct your std::string and use an std::back_inserter to fill it the lazy way. The std::back_inserter will perform some magic so that the result's push_back` method is called whenever an element has to be added:std::string find_intersection(std::string & first, std::string & second)
{
std::sort(std::begin(first),std::end(first));
std::sort(std::begin(second), std::end(second));
std::string result;
std::set_intersection(
std::begin(first), std::end(first),
std::begin(second), std::end(second),
std::back_inserter(result)
);
return result;
}Code Snippets
std::string find_intersection(std::string & first, std::string & second)
{
std::sort(std::begin(first),std::end(first));
std::sort(std::begin(second), std::end(second));
std::string result;
std::set_intersection(
std::begin(first), std::end(first),
std::begin(second), std::end(second),
std::back_inserter(result)
);
return result;
}Context
StackExchange Code Review Q#85581, answer score: 7
Revisions (0)
No revisions yet.