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

我已经对数组进行了排序,并创建了一个count数组,在这里我可以写出数组中每个单词的出现次数。
我的问题是整数数组元素和字符串数组元素的索引不一样如何根据整数数组的最大元素打印单词?

最佳答案

为了记录每个单词的计数,我会使用一个映射,将一个单词映射到它的当前计数。

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);

关于java - 编程珍珠中的词频,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2756714/

10-13 09:49