我正在尝试为我的类(class)构建一个 Vigenere 解密程序。这些指令要求程序能够解密多种语言。因此,我需要找出如何迭代字符串的哈希集并创建这些字符串中包含的字符数组以及每个字符出现的次数。我已经尝试了很长一段时间了,但我写的任何东西都不起作用。 `
public char mostCommonCharln(HashSet<String> dictionary) {
for (String s : dictionary) {
//what do I write here??? //
return Characters;
}
}
最佳答案
我假设您想要的签名是:
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;
}
这不是很有效,我编写它时没有尝试不同的输入,但它可以作为您的开始。
关于java - 如何从字符串哈希集创建字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36668735/