题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 读取输入
String str = in.nextLine();
// 处理输入
String[] strArr = str.split(" ");
// 获取单词数量
int size = Integer.parseInt(strArr[0]);
String[] words = new String[size];
// 获取单词数组
for (int i = 0; i < size; i++) {
words[i] = strArr[i + 1];
}
// 获取“兄弟单词”,并排序处理
String brotherWord = strArr[size + 1];
char[] brotherWordSorting = brotherWord.toCharArray();
Arrays.sort(brotherWordSorting);
String brotherWordSorted = new String(brotherWordSorting);
// 获取k
int k = Integer.parseInt(strArr[size + 2]);
// 统计兄弟单词数量,用一个有序数组存储
List<String> brotherWordsList = new ArrayList<>();
for (int i = 0; i < size; i++) {
if(words[i].equals(brotherWord)){
continue;
}
String wordSorting;
char[] thisWord = words[i].toCharArray();
Arrays.sort(thisWord);
String wordSorted = new String(thisWord);
if (words[i].length() == brotherWord.length() && wordSorted.equals(brotherWordSorted)) {
brotherWordsList.add(words[i]);
}
}
// 排序
brotherWordsList.sort(String::compareTo);
// 输出结果
System.out.println(brotherWordsList.size());
if (brotherWordsList.size() >= k) {
System.out.println(brotherWordsList.get(k - 1));
}
}
}
