字典树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;
    }
}



上一篇:JavaSE知识点:finalize,treeMap


下一篇:TreeMap排序