英文原文
Design a method to find the frequency of occurrences of any given word in a book. What if we were running this algorithm multiple times?
You should implement following methods:
WordsFrequency(book)
constructor, parameter is a array of strings, representing the book.get(word)
get the frequency ofword
in the book.
Example:
WordsFrequency wordsFrequency = new WordsFrequency({"i", "have", "an", "apple", "he", "have", "a", "pen"}); wordsFrequency.get("you"); //returns 0,"you" is not in the book wordsFrequency.get("have"); //returns 2,"have" occurs twice in the book wordsFrequency.get("an"); //returns 1 wordsFrequency.get("apple"); //returns 1 wordsFrequency.get("pen"); //returns 1
Note:
There are only lowercase letters in book[i].
1 <= book.length <= 100000
1 <= book[i].length <= 10
get
function will not be called more than 100000 times.
中文题目
设计一个方法,找出任意指定单词在一本书中的出现频率。
你的实现应该支持如下操作:
WordsFrequency(book)
构造函数,参数为字符串数组构成的一本书get(word)
查询指定单词在书中出现的频率
示例:
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
提示:
book[i]
中只包含小写字母1 <= book.length <= 100000
1 <= book[i].length <= 10
get
函数的调用次数不会超过100000
通过代码
高赞题解
class WordsFrequency {
private HashMap<String, Integer> map = new HashMap<>();
public WordsFrequency(String[] book) {
for (String word : book) {
map.put(word, map.getOrDefault(word, 0) + 1);
}
}
public int get(String word) {
return map.getOrDefault(word, 0);
}
}
统计信息
通过次数 | 提交次数 | AC比率 |
---|---|---|
15759 | 20638 | 76.4% |
提交历史
提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
---|