题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(); //单词数量
String[] arr = new String[n]; //单词数组
for (int i = 0; i < n; i++) {
arr[i] = in.next();
}
String x = in.next(); //目标单词
int k = in.nextInt(); //要求查的第k个字典序兄弟单词
//将x单词字母排序
String sortedX = sortStr(x);
//依次比较每个单词
List<String> res = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (x.length() != arr[i].length()) {
continue;
}
if (x.equals(arr[i])) {
continue;
}
if (sortedX.equals(sortStr(arr[i]))) {
res.add(arr[i]);
}
}
System.out.println(res.size());
Collections.sort(res);
if (res.size() >= k) {
System.out.println(res.get(k - 1));
}
}
//将单词按字母排序
public static String sortStr(String str) {
char[] arr = str.toCharArray();
Arrays.sort(arr);
return new String(arr);
}
}
