思路
- 统计
target中每个字符的次数(记,为
)
- 遍历字典
words- 当前单词中字符出现次数和
target中一致(对应isBrother方法),且和target不同,说明二者是“兄弟”,则使用list收集当前单词word
- 当前单词中字符出现次数和
- 最终
list中的元素个数,即为“兄弟单词个数”。若list中元素个数大于,则排序后取第
个元素
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 输入
int n = in.nextInt();
String[] words = new String[n];
for (int i = 0; i < n; i++) {
words[i] = in.next();
}
String target = in.next();
int k = in.nextInt();
// 统计 target 中每个字符的次数
Map<Character, Integer> map = new HashMap<>();
for (char c : target.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
int sum = 0;
List<String> list = new ArrayList<>();
for (String word : words) {
if (isBrother(word, map) && !word.equals(target)) {
list.add(word);
}
}
System.out.println(list.size());
if (list.size() >= k) {
Collections.sort(list);
System.out.println(list.get(k - 1));
}
in.close();
}
static boolean isBrother(String s, Map<Character, Integer> map) {
Map<Character, Integer> cntMap = new HashMap<>();
for (char c : s.toCharArray()) {
cntMap.put(c, cntMap.getOrDefault(c, 0) + 1);
}
if (cntMap.size() != map.size()) {
return false;
}
for (char key : cntMap.keySet()) {
if (cntMap.get(key) != map.getOrDefault(key, 0)) {
return false;
}
}
return true;
}
}

京公网安备 11010502036488号