Use Map Reduce to find anagrams in a given list of words.
Have you met this question in a real interview?
Yes
Example
Given["lint", "intl", "inlt", "code"]
, return["lint", "inlt", "intl"],["code"]
.
Given["ab", "ba", "cd", "dc", "e"]
, return["ab", "ba"], ["cd", "dc"], ["e"]
.
/**
* Definition of Input:
* template<class T>
* class Input {
* public:
* bool done();
* // Returns true if the iteration has elements or false.
* void next();
* // Move to the next element in the iteration
* // Runtime error if the iteration has no more elements
* T value();
* // Get the current element, Runtime error if
* // the iteration has no more elements
* }
*/
class AnagramMapper: public Mapper {
public:
void Map(Input<string>* input) {
// Write your code here
// Please directly use func 'output' to output
// the results into output buffer.
// void output(string &key, string& value);
while (!input->done()) {
string key = input->value();
sort(key.begin(), key.end());
output(key, input->value());
input->next();
}
}
};
class AnagramReducer: public Reducer {
public:
void Reduce(string &key, Input<string>* input) {
// Write your code here
// Please directly use func 'output' to output
// the results into output buffer.
// void output(string &key, vector<string>& value);
vector<string> res;
while (!input->done()) {
res.push_back(input->value());
input->next();
}
output(key, res);
}
};