import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String curLine = in.nextLine(); String[] strAry = curLine.split(" "); int count = Integer.parseInt(strAry[0]); String[] ary = new String[count]; for (int i = 1; i <= count; i++) { ary[i - 1] = strAry[i]; } String x = strAry[count + 1]; int k = Integer.parseInt(strAry[count + 2]); brotherWord(ary, x, k); } } private static void brotherWord(String[] words, String x, int k) { if (x == null || "".equals(x) || words == null || words.length == 0 || k < 0 || k > words.length) { System.out.println(0); System.out.println(""); return; } char[] xAry = x.toCharArray(); Map<Character, Integer> xMap = new HashMap<>(); for (int i = 0; i < xAry.length; i++) { xMap.put(xAry[i], xMap.getOrDefault(xAry[i], 0) + 1); } List<String> resList = new ArrayList<>(); for (int i = 0; i < words.length; i++) { String s = words[i]; if (s.equals(x) || s.length() != x.length()) { continue; } if (isBrotherWord(s, xMap)) { resList.add(s); } } if (resList.isEmpty()) { System.out.println(0); System.out.println(); } else { Collections.sort(resList); System.out.println(resList.size()); if (k - 1 >= resList.size() || k - 1 < 0) { System.out.println(); } else { System.out.println(resList.get(k - 1)); } } } /** * 交换该单词字母顺序(注:可以交换任意次),而不添加、删除、修改原有的字母就能生成的单词。 * 换种思路,其实只要每个字符出现的次数一样就可以了 * * @param s * @param xMap * @return */ private static boolean isBrotherWord(String s, Map<Character, Integer> xMap) { char[] sAry = s.toCharArray(); Map<Character, Integer> sMap = new HashMap<>(); List<Character> keys = new ArrayList<>(); for (int i = 0; i < sAry.length; i++) { sMap.put(sAry[i], sMap.getOrDefault(sAry[i], 0) + 1); if (!keys.contains(sAry[i])) { keys.add(sAry[i]); } } for (int i = 0; i < keys.size(); i++) { char cur = keys.get(i); if (!Objects.equals(sMap.get(cur), xMap.get(cur))) { return false; } } return true; } }