题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int number = in.nextInt();
List<String> list = new ArrayList<>();
// 注意 hasNext 和 hasNextLine 的区别
while (number > 0) { // 注意 while 处理多个 case
list.add(in.next());
number--;
}
String a = in.next();
int printRow = in.nextInt();
List<String> bros = isBro(a, list);
String[] array = bros.toArray(new String[0]);
sort(array);
System.out.println(bros.size());
if (array.length > printRow && null != array[printRow - 1]) {
System.out.println(array[printRow - 1]);
}
}
private static void sort(String[] param) {
Arrays.sort(param, new Comparator<String>() {
public int compare(String a, String b) {
int pos = 0;
while (pos < a.length() || pos < b.length()) {
if (a.length() < pos + 1) {
return -1;
}
if (b.length() < pos + 1) {
return 1;
}
if (a.charAt(pos) == b.charAt(pos)) {
pos++;
continue;
}
return a.charAt(pos) > b.charAt(pos) ? 1 : -1;
}
return 0;
}
});
}
private static List<String> isBro(String a, List<String> param) {
Map<Character, Integer> dic = new HashMap<>();
List<Integer> counter = new ArrayList<>();
int pos = 0;
for (int i = 0; i < a.length(); i++) {
char cha = a.charAt(i);
if (null == dic.get(cha)) {
dic.put(cha, pos);
counter.add(1);
pos++;
} else {
counter.set(dic.get(cha), counter.get(dic.get(cha)) + 1);
}
}
List<String> res = new ArrayList<>();
for (String b : param) {
if (filter(a, b, counter, dic)) {
res.add(b);
}
}
return res;
}
private static boolean filter(String a, String b, List<Integer> counterA,
Map<Character, Integer> dic) {
List<Integer> counter = new ArrayList<>(counterA);
if (a.length() != b.length()) {
return false;
}
for (int i = 0; i < b.length(); i++) {
char cha = b.charAt(i);
if (null == dic.get(cha)) {
return false;
}
int count = counter.get(dic.get(cha)) - 1;
if (count < 0) {
return false;
}
counter.set(dic.get(cha), count);
}
for (Integer count : counter) {
if (count != 0) {
return false;
}
}
if (b.equals(a)) {
return false;
}
return true;
}
}

智元机器人成长空间 174人发布