Skip to content

Instantly share code, notes, and snippets.

@mhx
Created December 6, 2012 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhx/4221177 to your computer and use it in GitHub Desktop.
Save mhx/4221177 to your computer and use it in GitHub Desktop.
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <string>
using namespace std;
void merge(vector<string>& v)
{
bool any;
do
{
size_t i = 0;
any = false;
while (i < v.size())
{
size_t j = i + 1;
while (j < v.size())
{
if (v[i].find_first_of(v[j]) != string::npos)
{
sort(v[i].begin(), v[i].end());
sort(v[j].begin(), v[j].end());
string tmp;
set_union(v[i].begin(), v[i].end(),
v[j].begin(), v[j].end(),
std::back_inserter(tmp));
v[i] = tmp;
v.erase(v.begin() + j);
any = true;
}
else
{
++j;
}
}
++i;
}
}
while (any);
}
int main()
{
vector<string> v;
v.push_back("abc");
v.push_back("def");
v.push_back("cf");
v.push_back("ghi");
v.push_back("jkl");
v.push_back("mno");
v.push_back("pqtl");
merge(v);
for (const std::string& s : v)
{
cout << s << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment