【问题标题】:Word frequency in Programming Pearls编程珍珠中的词频
【发布时间】:2010-05-03 07:36:11
【问题描述】:

在“编程珍珠”中,我遇到了以下问题。问题是这样的:“按频率递减的顺序打印单词”。据我了解问题是这样的。假设有一个给定的字符串数组,我们称它为s(单词我是随机选择的,没关系),

String s[]={"cat","cat","dog","fox","cat","fox","dog","cat","fox"};

我们看到字符串“cat”出现了 4 次,“fox”出现了 3 次,“dog”出现了 2 次。所以想要的结果是这样的:

cat
fox
dog

我用 Java 编写了以下代码:

import java.util.*;
public class string {
   public static void main(String[] args){
      String s[]={"fox","cat","cat","fox","dog","cat","fox","dog","cat"};
      Arrays.sort(s);
      int counts;
      int count[]=new int[s.length];
      for (int i=0;i<s.length-1;i++){
         counts=1;
         while (s[i].equals(s[i+1])){
            counts++;
         }
         count[i]=counts;
      }
   }
}

我已经对数组进行了排序并创建了一个计数数组,我在其中写入了数组中每个单词的出现次数。

我的问题是不知何故整数数组元素和字符串数组元素的索引不一样。如何根据整数数组的最大元素打印单词?

【问题讨论】:

  • davit-datuashvili,你能整理一下你的帖子吗?修复一些拼写错误并缩进您的代码,使其格式正确显示。见:stackoverflow.com/editing-help
  • 人们喜欢标点符号,就像计算机一样。 ;v)
  • 请告诉我如何使它更具可读性?
  • 首先,突出显示您的代码并单击“代码”按钮(“101010”图标)。
  • 我在清理、格式化和减少缩进方面做了一些尝试。

标签: java algorithm word-frequency


【解决方案1】:

为了跟踪每个单词的计数,我会使用 Map 将单词映射到它的当前计数。

String s[]={"cat","cat","dog","fox","cat","fox","dog","cat","fox"};

Map<String, Integer> counts = new HashMap<String, Integer>();
for (String word : s) {
    if (!counts.containsKey(word))
        counts.put(word, 0);
    counts.put(word, counts.get(word) + 1);
}

要打印结果,请遍历映射中的键并获取最终值。

for (String word : counts.keySet())
    System.out.println(word + ": " + (float) counts.get(word) / s.length);

【讨论】:

  • 另一种计算单词出现次数的方法是Collections.frequency,但在这种情况下它会有更高的BigO。
  • 很高兴知道。我查看了该函数的 Arrays :) 我想可以通过 Arrays.asList 获得最短的解决方案:) ...或者使用 Scala ;)
  • 好的,我也遇到了以下问题,例如给定两个文本,找到两个都出现的最长字符串将是最大的打印有没有快速的方法?
  • @david:这是经典的 LCS en.wikipedia.org/wiki/Longest_common_substring
  • 我不确定这是否能回答问题 - 以递减的频率打印单词。 HashMap 的迭代顺序是不确定的,因此单词会以任意顺序打印。
猜你喜欢
  • 1970-01-01
  • 2012-08-13
  • 2011-12-08
  • 2016-11-04
  • 1970-01-01
  • 2012-10-26
  • 1970-01-01
  • 2015-09-06
  • 2011-07-28
相关资源
最近更新 更多