题解 | 查找兄弟单词
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
#include <functional>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
bool isBrother(const string&S,const string &T){
if(S.size()!=T.size())return false;
if(S==T)return false;
int visitedS[10]={0};
int visitedT[10]={0};
int count=0;
for(int i=0;i<S.size();i++){
for(int j=0;j<T.size();j++){
if(visitedS[i]==0&&visitedT[j]==0&& S[i]==T[j]){
count++;
visitedS[i]=1;
visitedT[j]=1;
}
if(count==S.size())return true;
}
}
return false;
}
int main() {
int n;cin>>n;
vector<string>s_box;
while (n--) {
string s;
cin>>s;
s_box.push_back(s);
}
string x;cin>>x;
int k;cin>>k;
priority_queue<string,vector<string>,greater<string>>que;
for(string s:s_box){
if(isBrother(s,x))que.push(s);
}
cout<<que.size()<<endl;
if(que.size()!=0&&k<=que.size()){
k--;
while(k--)que.pop();
cout<<que.top()<<endl;}
}
// 64 位输出请用 printf("%lld")
原始思路:优先队列排序,简单但开销大,就当练手了。
抄袭来的思路:用mutiset先排序,遍历的时候同时计数和寻找目标值。
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
bool isBrotherWord(string s1, string s2) {
if (s1 == s2) {
return false;
}
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
if (s1 == s2) {
return true;
} else {
return false;
}
}
int main() {
int n;
cin >> n;
multiset<string> str_set;
while(n > 0) {
string s;
cin >> s;
str_set.insert(s);
n--;
}
string x;
cin >> x;
int k;
cin >> k;
int count = 0;
string res;
for(auto s : str_set) {
if (isBrotherWord(s, x)) {
count++;
k--;
if (k == 0) {
res = s;
}
}
}
cout << count << endl;
if (!res.empty()) {
cout << res << endl;
}
return 0;
}
