设计一个方法,找出任意指定单词在一本书中的出现频率。
你的实现应该支持如下操作:
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
java代码:
class Trie {
int val;
Trie[] son;
public Trie() {
this.val = 0;
this.son = new Trie[26];
}
}
public class WordsFrequency {
Trie root;
public WordsFrequency(String[] book) {
// 初始化根节点
this.root = new Trie();
Trie tmp = root;
for (String s : book) {
// 每次遍历到下一个word,Trie树都回到root结点开始遍历
tmp = root;
for (char c : s.toCharArray()) {
int next = c - 'a';
// 如果当前结点的son结点中不含有next字符
if (tmp.son[next] == null) {
tmp.son[next] = new Trie();
}
tmp = tmp.son[next];
}
// 遍历完该词汇后,在叶子节点处将val+1
tmp.val++;
}
}
public int get(String word) {
Trie find = root;
for (char c : word.toCharArray()) {
int next = c - 'a';
if (find.son[next] != null) {
find = find.son[next];
}
else {
return 0;
}
}
return find.val;
}
}
/**
* Your WordsFrequency object will be instantiated and called as such:
* WordsFrequency obj = new WordsFrequency(book);
* int param_1 = obj.get(word);
*/