题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
private static List<String> brothers = new ArrayList<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int n = in.nextInt();
String[] dics = new String[n];
for (int i = 0; i < n; i++) {
dics[i] = in.next();
}
String word = in.next();
int index = in.nextInt();
char[] chars = word.toCharArray();
// 1 输出可能的兄弟单词,在已提供的字典单词中筛选兄弟单词
// 1.1 求解单词的可能的兄弟单词:解析出各个字母(含重复字母),按字典序排列组合
solution(chars, 0);
brothers.remove(word);
int count = 0;
List<String> targets = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (brothers.contains(dics[i])) {
count++;
targets.add(dics[i]);
}
}
System.out.println(count);
// 3 按字典序列输出index的兄弟单词
String[] targetsInOrder = targets.toArray(new String[]{});
Arrays.sort(targetsInOrder);
if (index <= targetsInOrder.length) {
System.out.println(targetsInOrder[index - 1]);
}
}
}
public static void solution(char[] chars, int begin) {
if (begin >= chars.length) {
return;
}
if (begin == chars.length - 1) {
brothers.add(String.valueOf(chars));
return;
}
for (int j = begin; j < chars.length; j++) {
if (checkIfCanSwap(chars, begin, j)) {
swap(chars, begin, j);
solution(chars, begin + 1);
swap(chars, begin, j);
}
}
}
public static boolean checkIfCanSwap(char[] chars, int begin, int end) {
for (int i = begin; i < end; i++) {
if (chars[begin] == chars[end]) {
return false;
}
}
return true;
}
public static void swap(char[] chars, int i, int j) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
联想公司福利 1503人发布
查看22道真题和解析