LintCode 503: Anagram (Map Reduce) (System Design 题)

本文介绍了一种利用std::sort函数对字符串进行排序的方法,以优化字谜(anagram)查找算法。通过将单词排序后作为键值,可以高效地识别和归类字谜。文章详细解释了如何在映射器(Map)和归约器(Reduce)中应用此技巧,以实现大规模数据集上的字谜匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意std::sort()可以对string排序。我们可以把一个word排序后的新word作为key。

/**
 * 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()) {
            stringstream ss;
            string word;
            ss << input->value();
            while(ss >> word) {
                string sortedWord(word);
                sort(sortedWord.begin(), sortedWord.end());
                output(sortedWord, word);
            }
            input->next();
        }
    }
};


class AnagramReducer: public Reducer {
public:
    void Reduce(string &key, Input<string>* input) {
        // Please directly use func 'output' to output 
        // the results into output buffer.
        // void output(string &key, vector<string>& value);
        vector<string> result;
        while(!input->done()) {
            result.push_back(input->value());               
            input->next();
        }
        output(key, result);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值