题目
设计一个方法,找出任意指定单词在一本书中的出现频率。
你的实现应该支持如下操作:
WordsFrequency(book)构造函数,参数为字符串数组构成的一本书
get(word)查询指定单词在书中出现的频率
思路
1、用哈希表
2、构造一棵字典树,将单词的频次记录下来。然后再去获取对应的单词的频次即可。
代码
class WordsFrequency {
Trie trie = new Trie();// 构建一棵字典树
// 将所有的单词存放进入字典树
public WordsFrequency(String[] book) {
int length = book.length;
for (int i=0;i<length;++i)
{
trie.insertWord(book[i]);
}
}
// 获取对应单词的频次
public int get(String word)
{
return trie.getNum(word);
}
}
class Trie
{
private Trie children[]; // 当前节点的子节点
private int n; // 当前单词的频次
public Trie[] getChildren() {
return children;
}
public void setChildren(Trie[] children) {
this.children = children;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
// 初始化一个Trie节点
public Trie()
{
children =new Trie[26];
n=0;
}
public void insertWord(String word)
{
Trie root = this;
int length = word.length();
for (int i=0;i<length;++i)
{
char temp=word.charAt(i);
int index = temp-'a';
if (root.getChildren()[index]==null) // 如果当前字典树没有该节点,就构造一个
{
root.getChildren()[index]=new Trie();
}
root=root.getChildren()[index]; //移动根节点
}
++root.n; // 遍历完一个单词之后,增加对应的词数
}
public int getNum(String word)
{
Trie root = this;
int length = word.length();
for (int i=0;i<length;++i)
{
char temp =word.charAt(i);
int index = temp -'a';
if (root.getChildren()[index]!=null)
root=root.getChildren()[index];
else // 一旦搜索字典树的过程中有哪一个节点是空缺的,就返回0
return 0;
}
return root.getN(); // 搜索到最后,返回节点的数值
}
}
结果
简单的一个字典树的题目,如果使用哈希表应该会更快!