引入HashMap 判断是否也是兄弟字符串
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String[] strArray = in.nextLine().split(" ");
int count = Integer.parseInt(strArray[0]);
String[] brotherWord = new String[count];
for (int i = 1; i < count + 1; i++) {
brotherWord [i - 1] = strArray[i];
}
String word = strArray[count + 1];
int index = Integer.parseInt(strArray[count + 2]);
findBrotherWord(brotherWord, word, index);
}
}
public static void findBrotherWord(String[] brotherWord, String word, int index) {
List<String> list = new ArrayList<>();
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < word.length(); i++) {
map.put(word.charAt(i), map.getOrDefault(word.charAt(i), 0) + 1);
}
for (String tt : brotherWord) {
if (isBrother(tt, word, map)) list.add(tt);
}
list.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
System.out.println(list.size());
if (list.size() >= index) {
System.out.println(list.get(index - 1));
}
}
public static boolean isBrother(String str1, String str2, Map<Character, Integer> map) {
if (str1.length() != str2.length())return false;
if (str1.equals(str2)) return false;
Map<Character, Integer> str1Map = new HashMap<>();
for (int i = 0; i < str1.length(); i++) {
str1Map.put(str1.charAt(i), str1Map.getOrDefault(str1.charAt(i), 0) + 1);
}
for (int i = 0; i < str1.length(); i++) {
if (map.get(str1.charAt(i)) != str1Map.get(str1.charAt(i))) return false;
}
return true;
}
}