题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 3 abc bca cab abc 1
String input = in.nextLine();
String[] split = input.split(" ");
int size = Integer.parseInt(split[0]);
int k = Integer.parseInt(split[split.length - 1]);
String target = split[size + 1];
String[] dic = new String[size];
for (int i = 0; i < size; i++) {
dic[i] = split[i + 1];
}
// 如果是兄弟单词就存入这就集合
List<String> list = new ArrayList<>();
for (String s : dic) {
if (isBrother(s, target)) {
list.add(s);
}
}
// 输出兄弟单词个数
System.out.println(list.size());
// 输出查找到的按照字典顺序排序后的第k个兄弟单词,没有符合第k个的话则不用输出
if (list.size() >= k) {
// 有的话才排序,节省性能
list.sort(String::compareTo); // 按字典顺序排序
System.out.println(list.get(k - 1));
}
}
private static boolean isBrother(String s, String target) {
if (s.length() != target.length())
return false; // 长度不同
if (s.equals(target))
return false; // 同一个单词
// 统计每个字母的个数
int[] sAccount = new int['z'];
int[] targetAccount = new int['z'];
for (int i = 0; i < s.length(); i++) {
sAccount[s.charAt(i)]++;
targetAccount[target.charAt(i)]++;
}
// 如果每个字母的个数相同,则是兄弟单词
return Arrays.equals(sAccount, targetAccount);
}
}

查看2道真题和解析