列表

详情


面试题 16.02. 单词频率

设计一个方法,找出任意指定单词在一本书中的出现频率。

你的实现应该支持如下操作:

示例:

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

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class WordsFrequency { public: WordsFrequency(vector<string>& book) { } int get(string word) { } }; /** * Your WordsFrequency object will be instantiated and called as such: * WordsFrequency* obj = new WordsFrequency(book); * int param_1 = obj->get(word); */

python3 解法, 执行用时: 252 ms, 内存消耗: 43.1 MB, 提交时间: 2022-11-12 11:26:23

class WordsFrequency:

    def __init__(self, book: List[str]):
        self.c = Counter(book)


    def get(self, word: str) -> int:
        return self.c[word]


# Your WordsFrequency object will be instantiated and called as such:
# obj = WordsFrequency(book)
# param_1 = obj.get(word)

上一题