《编程珍珠》中的词频
在《编程珍珠》中我遇到了以下问题。问题是这样的:“按照频率递减的顺序打印单词”。据我了解问题是这样的。假设有一个给定的字符串数组,我们称之为s
(我随机选择的单词,没关系),
String s[]={"cat","cat","dog","fox","cat","fox","dog","cat","fox"};
我们看到字符串“cat”出现了4次,“fox”出现了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;
}
}
}
我对数组进行了排序并创建了一个计数数组,在其中写入数组中每个单词出现的次数。
我的问题是,整数数组元素和字符串数组元素的索引不知何故不同。如何根据整数数组的最大元素打印单词?
In "Programming Pearls" I have met the following problem. The question is this: "print words in order of decreasing frequency". As I understand problem is this. Suppose there is a given string array, let's call it s
(words I have chosen randomly, it does not matter),
String s[]={"cat","cat","dog","fox","cat","fox","dog","cat","fox"};
We see that string "cat" occurs 4 times, "fox" 3 times and "dog" 2 times. So the desired result will be this:
cat
fox
dog
I have written the following code in 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;
}
}
}
I have sorted the array and created a count array where I write the number of occurrences of each word in array.
My problem is that somehow the index of the integer array element and the string array element is not the same. How can I print words according to the maximum elements of the integer array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了跟踪每个单词的计数,我将使用一个 Map 将单词映射到它的当前计数。
要打印结果,请遍历映射中的键并获取最终值。
To keep track of the count of each word, I would use a Map which maps a word to it's current count.
To print the result, go through the keys in the map and get the final value.