「Programming Pearls」では、次の問題に遭遇しました。問題はこれです:「単語を頻度の低い順に印刷する」。私が理解しているように、問題はこれです。与えられた文字列配列があると仮定して、それを呼び出しましょう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;
}
}
}
配列をソートし、配列内の各単語の出現回数を書き込むカウント配列を作成しました。
私の問題は、どういうわけか整数配列要素と文字列配列要素のインデックスが同じではないことです。整数配列の最大要素に従って単語を出力するにはどうすればよいですか?