[CareerCup] 17.9 Word Frequency in a Book 书中单词频率

 

17.9 Design a method to find the frequency of occurrences of any given word in a book. 

 

这道题让我们找书中单词出现的频率,那么首先需要搞清楚的问题是,只需要统计一个单词,还是多个单词。如果是一个单词的话,那直接就遍历所有单词直接统计即可,如果是多个,就需要建立哈希表来建立每个单词和其出现次数之间的映射,然后再来查找即可,参见代码如下:

 

unordered_map<string, int> make_dictionary(vector<string> book) {
    unordered_map<string, int> res;
    for (auto word : book) {
        for (auto &a : word) a = tolower(a);
        ++res[word];
    }
    return res;
}

int get_frequency(unordered_map<string, int> m, string word) {
    if (m.empty() || word.empty()) return -1;
    for (auto &a : word) a = tolower(a);
    return m[word];
}

 

CareerCup All in One 题目汇总

posted @ 2016-04-26 10:20  Grandyang  阅读(642)  评论(0编辑  收藏  举报
Fork me on GitHub