题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <unordered_map>
using namespace std;
bool isBrother(string& word, string& target){
if(word.size() != target.size()){
return false;
}
if(word == target){
return false;
}
unordered_map<char, int> dic;
for(int i = 0; i < target.size(); ++i){
++dic[target[i]];
}
for(int i = 0; i < word.size(); ++i){
if(dic.count(word[i])){
--dic[word[i]];
if(dic[word[i]] == 0){
dic.erase(word[i]);
}
}
else{
return false;
}
}
return dic.empty() ? true : false;
}
int main(int argc, char* argv[]){
int n;
cin >> n;
multiset<string> dic;
for(int i = 0; i < n; ++i){
string word;
cin >> word;
dic.insert(word);
}
string target;
cin >> target;
int k;
cin >> k;
int count = 0;
string kBrother;
for(auto word : dic){
if(isBrother(word, target)){
++count;
if(count == k){
kBrother = word;
}
}
}
cout << count << endl;
if(!kBrother.empty()){
cout << kBrother << endl;
}
return 0;
}