题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.*;
/**
* 输入:
* 6 cab ad abcd cba abc bca abc 1
* 输出:
* 3
* bca
* 说明:
* abc的兄弟单词有cab cba bca,所以输出3
* 经字典序排列后,变为bca cab cba,所以第1个字典序兄弟单词为bca
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String str = in.nextLine();
// 解析输入的字符串
String[] split = str.split(" ");
int length = split.length;
List<String> list = new ArrayList<>();
List<String> brotherList = new ArrayList<>();
int inTotal = Integer.parseInt(split[0]);
int count = 0;
for (String s : split) {
if (count > 0 && count <= inTotal) {
list.add(s);
}
count++;
}
String letter = split[length - 2]; // 目标单词
int order = Integer.parseInt(split[length - 1]); // 目标顺序
// 收集兄弟单词
for (String s : list) {
if (isBrother(s, letter)) {
brotherList.add(s);
}
}
System.out.println(brotherList.size()); //输出兄弟单词的数量
// 对兄弟单词排序
Collections.sort(brotherList);
if (brotherList.size() >= order) {
System.out.println(brotherList.get(order - 1));
}
}
}
/**
* 是否是兄弟单词
*/
private static boolean isBrother(String s, String letter) {
if (s.equals(letter)) {
return false;
}
char[] chars = s.toCharArray();
char[] chars1 = letter.toCharArray();
Arrays.sort(chars);
Arrays.sort(chars1);
return new String(chars).equals(new String(chars1));
}
}

三奇智元机器人科技有限公司公司福利 50人发布