[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];
}

 本文转自博客园Grandyang的博客,原文链接:书中单词频率[CareerCup] 17.9 Word Frequency in a Book ,如需转载请自行联系原博主。

相关文章
|
2月前
typora中的公式怎么在word里面正常显示,怎么问可以让chatgpt的公式在word里面正常显示
typora中的公式怎么在word里面正常显示,怎么问可以让chatgpt的公式在word里面正常显示
248 0
LeetCode contest 200 5475. 统计好三元组 Count Good Triplets
LeetCode contest 200 5475. 统计好三元组 Count Good Triplets
PAT (Basic Level) Practice (中文)- 1050 螺旋矩阵(25 分)
PAT (Basic Level) Practice (中文)- 1050 螺旋矩阵(25 分)
85 0
|
Perl Shell 存储
[LeetCode] Word Frequency 单词频率
Write a bash script to calculate the frequency of each word in a text file words.txt. For simplicity sake, you may assume: words.
1224 0