gold-16-2


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

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

  • 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

//leetcode submit region begin(Prohibit modification and deletion)
class WordsFrequency {

    private Trie root;

    class Trie {
        private Trie[] leafs;
        private int value;

        public Trie() {
            value = 0;
        }

        public void setValue(int v) {
            this.value = v;
        }

        public int getValue() {
            return this.value;
        }

        public Trie getLeaf(char ch) {
            if (leafs == null) {
                leafs = new Trie[26];
            }
            if (leafs[ch - 'a'] == null) {
                leafs[ch - 'a'] = new Trie();
            }
            return leafs[ch - 'a'];
        }
    }

    public WordsFrequency(String[] book) {
        this.root = new Trie();

        for (String b : book) {
            Trie node = root;
            for (int i = 0; i < b.length(); i++) {
                node = node.getLeaf(b.charAt(i));

                if (i == b.length() - 1) {
                    node.setValue(node.getValue() + 1);
                }
            }
        }
    }

    public int get(String word) {
        Trie node = root;
        for (int i = 0; i < word.length(); i++) {
            node = node.getLeaf(word.charAt(i));
        }

        return node.getValue();
    }
}
/**
 * Your WordsFrequency object will be instantiated and called as such:
 * WordsFrequency obj = new WordsFrequency(book);
 * int param_1 = obj.get(word);
 */
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !