题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
#include <algorithm>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
// 通过排序算法判断是否是兄弟单词。
bool isBro(string s1, string s2){
// 首先看长度是否一样,长度一样才有可能
if(s1.length() != s2.length()){
return false;
}
// 然后看是否是相同的字符串,相同字符串则不是兄弟单词
if(s1 == s2){
return false;
}
// 最后我们对两个字符串分别以各自的字符排序,这样两个字符串都是一样的顺序,只要字符集和各个字符数量对得上,排序出来的单词应该是一样的,这就是兄弟单词。
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
return s1==s2;
}
int main() {
int n;
cin >> n;
string str;
// vector保存输入的全部单词,
vector<string> v;
for(int i = 0; i < n; i++){
cin >> str;
v.push_back(str);
}
cin >> str;
cin >> n;
vector<string> s;
// 遍历这个vector,对每一个单词判断是否是str的兄弟单词
for(auto it : v){
if(!isBro(it, str)){
continue;
}
s.push_back(it);
}
sort(s.begin(), s.end());
cout << s.size() << endl;
if(s.size()>0){
cout << s[n-1] << endl;
}
return 0;
}
// 64 位输出请用 printf("%lld")

