题解 | #查找兄弟单词#
查找兄弟单词
http://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
#include<bits/stdc++.h>
using namespace std;
static bool cmp(string &a, string &b) {
int i;
for (i = 0; i < a.size() && i < b.size(); i++) {
if (a[i] < b[i]) {
return true;
}
else if (a[i] > b[i]) {
return false;
}
}
if (a.size() < b.size()) return true;
else return false;
}
void func(vector<string> &vec, string &target, int targetNum) {
vector<int> label(26, 0);
vector<string> bro;
int sum = 0;
for (auto &ch : target) {
label[ch - 'a']++;
sum++;
}
for (auto str1 : vec) {
vector<int> labelTemp = label;
bool isBro = true;
if (str1 == target || str1.size() != target.size()) {
continue;
}
for (auto ch : str1) {
labelTemp[ch - 'a']--;
if(labelTemp[ch - 'a'] < 0) {
isBro = false;
break;
}
}
if (isBro) {
bro.push_back(str1);
}
}
sort(bro.begin(), bro.end(), cmp);
cout << bro.size() << endl;
if (bro.size() >= targetNum) {
cout << bro[targetNum - 1]<<endl;
}
}
int main() {
int n;
vector<string> vec;
string target;
int targetNum;
while (cin >> n) {
while (n--) {
string str;
cin >> str;
vec.push_back(str);
}
cin >> target;
cin >> targetNum;
}
func(vec,target, targetNum);
}