leetcode 1315.祖父结点值为偶数的和
1.题目要求:
2.题目实列:
WordsFrequency wordsFrequency = new WordsFrequency({"i", "have", "an", "apple", "he", "have", "a", "pen"});
wordsFrequency.get("you"); //返回0,"you"没有出现过
wordsFrequency.get("have"); //返回2,"have"出现2次
wordsFrequency.get("an"); //返回1
wordsFrequency.get("apple"); //返回1
wordsFrequency.get("pen"); //返回1
3.做题步骤:
巧妙运用map容器求次数
4.题目代码:
class WordsFrequency {
public:
//使用map容器,把每个单词的频率统计出来
map<string,int> word_count;
WordsFrequency(vector<string>& book) {
for(int i = 0;i < book.size();i++){
map<string,int> :: iterator it = word_count.find(book[i]);
if(it != word_count.end()){
it->second += 1;
}else{
word_count.insert(make_pair(book[i],1));
}
}
}
int get(string word) {
//返回单词频率
map<string,int> :: iterator it = word_count.find(word);
if(it != word_count.end()){
return it->second;
}else{
return 0;
}
}
};
/**
* Your WordsFrequency object will be instantiated and called as such:
* WordsFrequency* obj = new WordsFrequency(book);
* int param_1 = obj->get(word);
*/