本题涉及的关键点主要有:1.如果判断一个单词是否是兄弟单词,2.如果对所有的兄弟单词按照字典序进行排序。对于第一点,这里利用unordered_map记录单词x中的所有字母以及对应个数,如果在单词word中没找到一个匹配的字母,就删去unordered_map中的对应次数,当某个单词的次数为0时表示该单词匹配结束。如果出现匹配不到对应字母或者匹配次数已经为0时,匹配失败,表示该单词不是兄弟单词。字典序排序利用sort函数的cmp即可实现。
#include <string>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
bool judge_broWords(string word, string x) {
if (word == x) return false;
if (word.size() != x.size()) return false;
else {
unordered_map<char, int> u_map;
for (int j = 0; j < x.size(); j++) {
u_map[x[j]]++;
}
for (int i = 0; i < word.size(); i++) {
if (u_map.find(word[i]) != u_map.end()) {
// 在word中找到一个与x中相同的字符
if (u_map[word[i]] == 0) {
return false;
} else {
u_map[word[i]]--;
}
} else {
// 没有找到与之匹配的字符
return false;
}
}
return true;
}
}
static bool cmp(const string &a, const string &b) {
return a < b;
}
int main() {
int n = 0;
cin >> n;
vector<string> dict;
for (int i = 0; i < n; i++) {
string temp;
cin >> temp;
dict.push_back(temp);
}
string x;
cin >> x;
int k = 0;
cin >> k;
vector<string> bro_words;
for (vector<string>::iterator iter = dict.begin(); iter != dict.end(); iter++) {
string word = *iter;
if (judge_broWords(word, x)) {
bro_words.push_back(word);
}
}
// 输出
if (bro_words.size() == 0) {
cout << bro_words.size() << endl;
}
else {
sort(bro_words.begin(), bro_words.end(), cmp);
cout << bro_words.size() << endl;
cout << bro_words[k - 1] << endl;
}
return 0;
}