字典树3.输出频率前k的单词(字典树+treemap)

这个list简直了,很厉害。

import java.util.*;

public class Main {
    public static void main(String[] argc){

        String[] reviews={"i love python and cpp", "i love java", "i love python more than go but go is nice as well", "python is great", "i love cpp", "i love java so much"};
        String[] languages = {"python", "java","cpp", "go"};
        int k = 2;
        int res=0;
        Trie trie=new Trie();
        for(String s:languages){
            trie.insert(s);
        }
        Map<String,Integer> map=new TreeMap<String,Integer>();
        for(String s:reviews){
            String[] words=s.split(" ");
           for(String word:words){
               if(trie.serch(word)){
                   map.put(word,map.getOrDefault(word,0)+1);
               }
           }
        }
        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
        Collections.sort(list,(o1,o2)->{
            if(o1.getValue()!=o2.getValue())return o2.getValue()-o1.getValue();
            else return o1.getKey().compareTo(o2.getKey());
        });
        int s=0;
        for (Map.Entry<String, Integer> e: list) {
            System.out.print(e.getKey()+" ");
            s++;
            if(s==k)break;
        }
    }
}
class Trie{
    class trieNode{
        trieNode[] next;
        boolean isEnd;
        public trieNode(){
            next=new trieNode[26];
            isEnd=false;
        }
    }
    trieNode root;
    public Trie(){
        root=new trieNode();
    }
    public void insert(String word){
        trieNode cur=root;
        char[] chars=word.toCharArray();
        for(int i=0;i<chars.length;i++){
            int index=chars[i]-'a';
            if(cur.next[index]==null){
                cur.next[index]=new trieNode();
            }
            cur=cur.next[index];
        }
        cur.isEnd=true;
    }
    public boolean serch(String word){
        char[] chars=word.toCharArray();
        trieNode cur=root;
        for(int i=0;i<chars.length;i++){
            int index=chars[i]-'a';
            if(cur.next[index]==null){
                return false;
            }
            cur=cur.next[index];
        }
        return cur.isEnd;
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值