题
在“编程珍珠”中,我遇到了以下问题。问题是:“按频率降低顺序打印单词”。据我了解,这是这个问题。假设有一个给定的字符串数组,让我们称呼它 s
(我随机选择的话,没关系),
String s[]={"cat","cat","dog","fox","cat","fox","dog","cat","fox"};
我们看到弦“猫”出现了4次,“狐狸” 3次,“狗” 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;
}
}
}
我已经对数组进行了排序,并创建了一个计数数组,其中我在数组中写下每个单词的出现数量。
我的问题是,整数数组元素的索引和字符串数组元素的索引不同。如何根据整数数组的最大元素打印单词?
解决方案
为了跟踪每个单词的计数,我将使用一个映射单词当前计数的地图。
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);
不隶属于 StackOverflow