题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
bool isBrother(string x, string vi);
int main() {
int n;
cin >> n;
string str;
vector<string>vec;
for (int i = 0; i < n; i++) {
cin >> str;
vec.push_back(str);
}
sort(vec.begin(), vec.end());
int k;
string x;
cin >> x ;
cin >> k;
int num = 0;
string ans;
for (int i = 0; i < n; i++) {
if (isBrother(x, vec[i])) {
num++;
k--;
if (k == 0) {
ans = vec[i];
}
}
}
cout << num << endl << ans;
}
bool isBrother(string x, string vi) {
map<char, int>m1, m2;
pair<char, int>p;
if (x.size() != vi.size() || x == vi)
return false;
for (int i = 0; i < x.size(); i++) {
if (m1.find(x[i]) != m1.end()) {
m1[x[i]] += 1;
} else {
p.first = x[i];
p.second = 1;
m1.insert(p);
}
}
for (int i = 0; i < vi.size(); i++) {
if (m1.find(vi[i]) != m1.end()) {
m1[vi[i]] -= 1;
} else {
return false;
}
}
for (auto i : m1) {
if (i.second != 0) {
return false;
}
}
return true;
}
