LintCode-499: Word Count (Map Reduce) (System Design题)
这题其实就是简单模拟字符串分块统计个数和归并的过程。
我用的stringstream来split字符串。
/*** Definition of Input:* template* 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 WordCountMapper: public Mapper {
public:void Map(Input* input) {// Please directly use func 'output' to // output the results into output buffer.// void output(string &key, int value);while(!input->done()) {stringstream ss;string word;ss << input->value();while(ss >> word) output(word, 1);input->next();}}
};class WordCountReducer: public Reducer {
public:void Reduce(string &key, Input<int>* input) {// Please directly use func 'output' to // output the results into output buffer.// void output(string &key, int value);int count = 0;while(!input->done()) {count += input->value();input->next();}output(key, count);}
};
jiuzhang给的答案是用split()函数,我觉得也不错。
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, int value);while (!input->done()) {vector<string> words = split(input->value(), " ");for (string word : words) {output(word, 1);}input->next();}}vector<string> split(const string &str, string delim) {vector<string> results;int lastIndex = 0, index;while ((index = str.find(delim, lastIndex)) != string::npos) {results.push_back(str.substr(lastIndex, index - lastIndex));lastIndex = index + delim.length();}if (lastIndex != str.length()) {results.push_back(str.substr(lastIndex, str.length() - lastIndex));}return results;}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
