面试题 16.02. 单词频率
设计一个方法,找出任意指定单词在一本书中的出现频率。
你的实现应该支持如下操作:
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就可以过,不过这个题目是想考察对一些数的数据结构的掌握,于是写了个字典树,字典树具有单词计数的功能,提交就通过,算是字典树的模板题吧。
AC代码
class WordsFrequency {
public:
int trie[1000000][26] = {0};
int color[1000000] = {0};
int k = 1;
void insert(string w){
int p = 0;
for(int i=0; i<w.length(); i++){
int c = w[i] - 'a';
if(!trie[p][c]){
trie[p][c] = k;
k++;
}
p = trie[p][c];
}
color[p]++;
}
int search(string s){
int p = 0;
for(int i=0; i<s.length(); i++){
int c = s[i] - 'a';
if(!trie[p][c]) return 0;
p = trie[p][c];
}
return color[p];
}
WordsFrequency(vector<string>& book)
{
for(int i=0;i<book.size();i++)
insert(book[i]);
}
int get(string word) {
return search(word);
}
};
/**
* Your WordsFrequency object will be instantiated and called as such:
* WordsFrequency* obj = new WordsFrequency(book);
* int param_1 = ob;j->get(word);
*/
5.31%。。。。。字典树这么慢的吗。。。。。