1 Star 0 Fork 332

[]~( ̄ ̄)~* / leetcode

forked from doocs / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README_EN.md 2.86 KB
一键复制 编辑 原始数据 按行查看 历史
ylb 提交于 2021-12-24 22:51 . style: format code and docs (#645)

16.02. Words Frequency

中文文档

Description

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 of word 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.

Solutions

Python3

class WordsFrequency:

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

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

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

Java

class WordsFrequency {

    private Map<String, Integer> counter = new HashMap<>();

    public WordsFrequency(String[] book) {
        for (String word : book) {
            counter.put(word, counter.getOrDefault(word, 0) + 1);
        }
    }

    public int get(String word) {
        return counter.containsKey(word) ? counter.get(word) : 0;
    }
}

/**
 * Your WordsFrequency object will be instantiated and called as such:
 * WordsFrequency obj = new WordsFrequency(book);
 * int param_1 = obj.get(word);
 */

JavaScript

/**
 * @param {string[]} book
 */
var WordsFrequency = function (book) {
    this.counter = {};
    for (const word of book) {
        this.counter[word] = (this.counter[word] || 0) + 1;
    }
};

/**
 * @param {string} word
 * @return {number}
 */
WordsFrequency.prototype.get = function (word) {
    return this.counter[word] || 0;
};

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

...

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/keshuimao/leetcode.git
git@gitee.com:keshuimao/leetcode.git
keshuimao
leetcode
leetcode
main

搜索帮助

344bd9b3 5694891 D2dac590 5694891