单词频率

题目描述

来源于 https://leetcode-cn.com/

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

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

  • 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

解法:

可以使用一个 map 统计词频,也可以使用一个 trie 来存储所有的单词,并统计词频。


struct Node{
    Node():count(0){}
    int count;
    Node* children[26]{};
};

class Trie{
private:
public:
    void insert(const string& word){
        Node *node = &root;
        for(auto ch: word){
            int i = ch - 'a';
            if(node->children[i] == nullptr){
                node->children[i] = new Node;
            }
            node = node->children[i];
        }
        node->count += 1;
    }

    int find(const string& word){
        Node *node = &root;
        for(auto ch: word){
            int i = ch - 'a';
            if(node->children[i]){
                node = node->children[i];
            }else{
                return 0;
            }
        }
        return node->count;
    }
private:
    Node root;
};


class WordsFrequency {
public:
    WordsFrequency(vector<string>& book) {
        for(auto& word: book){
            trie.insert(word);
        }
    }
    int get(string word) {
        return trie.find(word);
    }
private:
    Trie trie;
};