1

「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;
      }
   }
}

配列をソートし、配列内の各単語の出現回数を書き込むカウント配列を作成しました。

私の問題は、どういうわけか整数配列要素と文字列配列要素のインデックスが同じではないことです。整数配列の最大要素に従って単語を出力するにはどうすればよいですか?

4

1 に答える 1

7

各単語の数を追跡するには、単語を現在の数にマップする Map を使用します。

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);
于 2010-05-03T07:54:29.240 に答える