题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
比较简单,用哈希桶的方法记录每一位字母出现的次数就可以很方便地比较两字母是否为「兄弟单词」,把兄弟单词记录下来,排序,输出第 k 个就行。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
String[] dic = new String[n];
for(int i = 0; i < n; i++) {
dic[i] = in.next();
}
String x = in.next();
int k = in.nextInt();
int[] countX = new int[26];
for(char ch : x.toCharArray()) {
countX[ch-'a']++;
}
List<String> list = new ArrayList<>();
for(int i = 0; i < n; i++) {
String word = dic[i];
int[] count = new int[26];
if(word.equals(x)) continue;
for(char ch : word.toCharArray()) {
count[ch-'a']++;
}
int j;
for(j = 0; j < 26; j++) {
if(count[j] != countX[j]) break;
}
if(j == 26) list.add(word);
}
Collections.sort(list);
System.out.println(list.size());
if(k <= list.size()) System.out.println(list.get(k - 1));
}
}
}