1

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

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

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

4

1 回答 1

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);
于 2010-05-03T07:54:29.240 回答