示例代码:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 获取输入字符串
String[] strings = sc.nextLine().split(" ");
// 字典中单词个数
int n = Integer.parseInt(strings[0]);
// 获取单词 x
String x = strings[strings.length - 2];
int k = Integer.parseInt(strings[strings.length - 1]);
List<String> list = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (isBro(strings[i], x)) {
list.add(strings[i]);
}
}
// 兄弟单词数组按字典顺序排列
Collections.sort(list);
System.out.println(list.size());
if (k <= list.size()) {
System.out.println(list.get(k - 1));
}
}
/**
* 对比当前单词是否是兄弟单词
*
* @param str 当前但系
* @param x 单词 x
*/
public static boolean isBro(String str, String x) {
if (str.equals(x) || str.length() != x.length()) {
return false;
}
char[] ch1 = str.toCharArray();
char[] ch2 = x.toCharArray();
Arrays.sort(ch1);
Arrays.sort(ch2);
return new String(ch1).equals(new String(ch2));
}