描述
定义一个单词的"兄弟单词"为:交换该单词字母顺序(注:可以交换任意次),而不添加、删除、修改原有的字母就能生成的单词。
兄弟单词要求和原来的单词不同。例如: ab 和 ba 是兄弟单词。 ab 和 ab 则不是兄弟单词。
现在给定你 n 个单词,另外再给你一个单词 x ,让你寻找 x 的兄弟单词里,按字典序排列后的第 k 个单词是什么?
注意:字典中可能有重复单词。
数据范围
, 输入的字符串长度满足
,
输入描述
输入只有一行。 先输入字典中单词的个数n,再输入n个单词作为字典单词。 然后输入一个单词x 最后后输入一个整数k
输出描述:
第一行输出查找到x的兄弟单词的个数m 第二行输出查找到的按照字典顺序排序后的第k个兄弟单词,没有符合第k个的话则不用输出。
示例1
输入
3 abc bca cab abc 1
输出
2
bca
示例2
输入
6 cab ad abcd cba abc bca abc 1
输出
3
bca
说明:
abc的兄弟单词有cab cba bca,所以输出3
经字典序排列后,变为bca cab cba,所以第1个字典序兄弟单词为bca
代码
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.*;
public class Main {
static final Map<Character, Integer> WORD_MAP = new HashMap();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int wordCount = in.nextInt();
String[] words = new String[wordCount];
for (int i = 0; i < wordCount; i++) {
words[i] = in.next();
}
String word = in.next();
int k = in.nextInt();
// 第一种解法
initMap(word);
findBroWord(word, wordCount, words, k, Main::equalsMap);
// 第二种解法
String sortedWord = sort(word);
findBroWord(word, wordCount, words, k, w -> sort(w).equals(sortedWord));
}
static void findBroWord(String word, int wordCount, String[] words, int k, Predicate<String> predicate) {
List<String> broWordList = new ArrayList<>();
for (int i = 0; i < wordCount; i++) {
if (maybeBrother(word, words[i]) && !words[i].equals(word)) {
if (predicate.test(word)) {
broWordList.add(words[i]);
}
}
}
// 按字典序升序
List<String> sortedBroWordList = broWordList.stream().sorted().toList();
int size = sortedBroWordList.size();
int idx = k - 1;
System.out.println(size + "\n" + (idx < size ? sortedBroWordList.get(idx) : ""));
}
static void initMap(String word) {
for (int i = 0; i < word.length(); i++) {
WORD_MAP.compute(word.charAt(i), (k, v) -> v == null ? 1 : v + 1);
}
}
static boolean equalsMap(String word) {
Map<Character, Integer> wordMap = new HashMap<>();
for (int i = 0; i < word.length(); i++) {
wordMap.compute(word.charAt(i), (k, v) -> v == null ? 1 : v + 1);
}
for (Map.Entry<Character, Integer> entry : WORD_MAP.entrySet()) {
if (!wordMap.containsKey(entry.getKey())) {
return false;
} else {
if (!wordMap.get(entry.getKey()).equals(entry.getValue())) {
return false;
}
}
}
return true;
}
static boolean maybeBrother(String s1, String s2) {
return s1.length() == s2.length();
}
static String sort(String str) {
return Stream.of(str.split("")).sorted().collect(Collectors.joining());
}
}