Word Frequencies:统计字符串数组中某个单词出现的次数。
因为必须要对整个字符串数组进行遍历,所以至少需要O(n)
的时间。但是如果该函数会多次调用的话,可以使用另外的数据结构将字符串数组组织起来,达到更高的效率。
class WordsFrequency {
private:
unordered_map<string, size_t> hash;
public:
WordsFrequency(vector<string>& book) {
for(const string &word : book)
{
hash[word]++;
}
}
int get(string word) {
unordered_map<string, size_t>::const_iterator citer;
citer = hash.find(word);
if(citer == hash.end()) return 0;
else return citer->second;
}
};
/**
* Your WordsFrequency object will be instantiated and called as such:
* WordsFrequency* obj = new WordsFrequency(book);
* int param_1 = obj->get(word);
*/