java - 在字典中找出三个最常见的词

标签 java algorithm dictionary data-structures heap

问题是找出字典中最常见的三个单词。我想出了下面的代码,但由于某种原因它不起作用(我的意思是当我尝试在 eclipse 中运行它时,它直接引导我进入调试页面,尽管我在编译器屏幕上没有收到任何错误),我调试后找不到原因。你能帮我找出问题所在吗?

Exception in thread "main" java.lang.NullPointerException at java.util.PriorityQueue.offer
(Unknown Source) at java.util.PriorityQueue.add
(Unknown Source) at generalquestions.MostCommonWords.mostCommonStringFinder
(MostCommonWords.java:41) at generalquestions.MostCommonWords.main
(MostCommonWords.java:61)

  public static Queue<Integer> mostCommonStringFinder (String document, int k){

    if (document == null){
        throw new IllegalArgumentException();
    }
    if (document.isEmpty()){
        throw new IllegalArgumentException("Document is empty");
    }   

    String [] wordHolder = document.split(" ");     

    HashMap<String, Integer> map = new HashMap<String, Integer>();


    for (String s : wordHolder){

        if (!map.containsKey(s)){
            map.put(s, 1);

        }
        else{
            int value = map.get(s);
            value++;
            map.put(s, value);
        }           
    }

    Queue<Integer> minHeap = new PriorityQueue<>();

    for ( int i = 0 ; i < k ; i++){

        minHeap.add(map.get(i));            
    }       

    for(int j = k ; j < map.size() ; j++){

        if(map.get(j) > minHeap.peek()){
            minHeap.poll();
            minHeap.add(map.get(j));
        }
    }

    return minHeap;

}

最佳答案

mapHashMap<String, Integer> ,因此键是字符串,即文本中的单词。

map.get(i)将始终返回 null , 因为没有 Integer map 中的键。


自从您返回 Queue<Integer>我假设期望值最高 k字数,所以替换所有来自 Queue<Integer> minHeap 的内容并继续:

List<Integer> counts = new ArrayList<>(map.values());
Collections.sort(counts, Collections.reverseOrder());
return counts.subList(0, k);

并将返回类型更改为 List<Integer> .

测试

String text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " +
              "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, " +
              "quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo " +
              "consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse " +
              "cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat " +
              "non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
System.out.println(mostCommonStringFinder(text, 3));

输出

[3, 2, 2]

关于java - 在字典中找出三个最常见的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33047332/

相关文章:

java - Hibernate 不自动创建表

java - 用Java读取CSV文件并存储数据

algorithm - 独立访客数模块

iphone - 在字符串中存储单词的优雅算法

json - swift 对象映射器 : toJSONString for a dictonary containing mappable Object

python - 如何评估包含已定义函数的表达式并返回数值解

python - Python 是否优化了引擎盖下的字典查找?

java - 在属性文件中的 elasticsearch 中指定索引名称和索引类型

java - Spring 如何注入(inject)列表作为构造函数参数

algorithm - 使用常量存储总结无限序列