私はあなたが欲しい署名があると仮定します:
public static List<CharFrequency> mostCommonChars(Set<String> dictionary)
CharFrequency
クラスは次のように定義されて
:
class CharFrequency implements {
private char value;
private int count;
public CharFrequency(char v, int c) {
this.value = v;
this.count = c;
}
@Override
public String toString() {
return value + " -> " + count;
}
}
そして、あなたは以下の方法があります:
を
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.List;
import java.util.stream.Collectors;
import java.util.function.Function;
public static List<CharFrequency> mostCommonChars(Set<String> dictionary) {
// Concat all strings present in dictionary into a big string
String allchars = dictionary.stream().collect(Collectors.joining());
// Then convert it to a List<Character> which can use Java Streams
List<Character> charList = new ArrayList<>(allchars.length());
for (char c : allchars.toCharArray()) {
charList.add(c);
}
final List<CharFrequency> result = new ArrayList<>();
charList.stream()
// Group by the char itself and count occurrences
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.forEach((character, count1) -> result.add(new CharFrequency(character, count1)));
return result;
}
これはあまり効率的ではありません。私は別の入力を試みることなくそれを書いてきましたが、それはあなたの出発点として役立ちます。
は、あなたのメソッドのシグネチャによると、単一の 'char'を返すことになっています。メソッドの名前から、私は、メソッドが文字列内の最も出現頻度の高い文字を 'dictionary'で返すようにしたいと思いますか? – dpr
はい、この方法で期待されることを明確にしてください。 – totoro
ありがとうございました。不明な点がありましたら申し訳ありません。このメソッドは、文字列sで検出したすべての文字を返し、文字が何回発生したかを追跡します。例えば、AABBBCDDはA(2)B(3)C(1)D(2)を返します。私はこれを行う最良の方法は、配列に各オカレンスを追加することですが、ハッシュセットを反復することでこれを達成することは私を混乱させます(注 - コースの指示はfor(文字列s:辞書)を使用することを提案します – Ryan