编程珍珠中的字频率

时间:2010-05-03 07:36:11

标签: java algorithm word-frequency

在“编程珍珠”中,我遇到了以下问题。问题是:“按频率递减的顺序打印文字”。据我所知,问题是这个。假设有一个给定的字符串数组,我们称之为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;
      }
   }
}

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

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

1 个答案:

答案 0 :(得分:7)

为了跟踪每个单词的计数,我会使用一个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);