LeetCode——面试题 16.02. 单词频率

题目

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

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

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();           			// 搜索到最后,返回节点的数值
    }
}

结果

在这里插入图片描述
简单的一个字典树的题目,如果使用哈希表应该会更快!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值