gpt4 book ai didi

java - 想要统计Java中字符串的出现次数

转载 作者:行者123 更新时间:2023-12-02 04:49:57 25 4
gpt4 key购买 nike

所以我有一个 .txt 文件,我正在使用它调用

String[] data = loadStrings("data/data.txt");

文件已经排序,基本上看起来像:

Animal
Animal
Cat
Cat
Cat
Dog

我正在寻找一种算法来计算java中的排序列表,而不使用任何像Multisets这样的库或不使用Maps/HashMaps。到目前为止,我已经设法让它打印出出现次数最多的单词,如下所示:

ArrayList<String> words = new ArrayList();

int[] occurrence = new int[2000];
Arrays.sort(data);

for (int i = 0; i < data.length; i ++ ) {
words.add(data[i]); //Put each word into the words ArrayList
}
for(int i =0; i<data.length; i++) {
occurrence[i] =0;
for(int j=i+1; j<data.length; j++) {
if(data[i].equals(data[j])) {
occurrence[i] = occurrence[i]+1;
}
}
}
int max = 0;
String most_talked ="";
for(int i =0;i<data.length;i++) {
if(occurrence[i]>max) {
max = occurrence[i];
most_talked = data[i];
}
}
println("The most talked keyword is " + most_talked + " occuring " + max + " times.");

我想要的不仅仅是获得出现次数最多的单词(可能是前 5 名或前 10 名)。希望这已经足够清楚了。感谢您的阅读

最佳答案

既然你说你不想使用某种数据结构,我认为你可以做这样的事情,但它的性能不高。我通常更喜欢存储索引而不是值。

ArrayList<String> words = new ArrayList();

int[] occurrence = new int[2000];
Arrays.sort(data);


int nwords = 0;
occurrence[nwords]=1;
words.add(data[0]);
for (int i = 1; i < data.length; i ++ ) {
if(!data[i].equals(data[i-1])){ //if a new word is found
words.add(data[i]); //put it into the words ArrayList
nwords++; //increment the index
occurrence[nwords]=0; //initialize its occurrence counter
}
occurrence[nwords]++; //increment the occurrence counter
}

int max;
for(int k=0; k<5; k++){ //loop to find 5 times the most talked word
max = 0; //index of the most talked word
for(int i = 1; i<words.size(); i++) { //for every word
if(occurrence[i]>occurrence[max]) { //if it is more talked than max
max = i; //than it is the new most talked
}
}
println("The most talked keyword is " + words.get(max) + " occuring " + occurence[max] + " times.");
occurence[max]=0;
}

每次我找到具有较高出现值的值时,我都会将其出现计数器设置为 0,然后再次重复该数组,重复 5 次。

关于java - 想要统计Java中字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29323751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com