思路:
感觉可以爆搜找,用了暴力也做出来了,hash存一下测试单词的全排列,然后遍历测试的单词,如果在里面就存到ans中,最后输出ans.size()和 ans[k - 1]
代码:
#include<iostream>
#include<algorithm>
#include<unordered_set>
#include<string>
#include<vector>
using namespace std;
int n,k;
int main(){
cin>>n;
//存测试的单词
vector<string> Str;
for(int i = 0; i < n; i++){
string s;
cin>>s;
Str.push_back(s);
}
//存验证的单词 k是要求的排列第几个
string str;
cin>>str>>k;
//cout<<str<<k<<endl;
int len = str.size();
int fact = 1;
for(int i = 1; i <= len; i++) fact *= i;
string s = str;
sort(s.begin(),s.end());
//hash存全排列
unordered_set<string> hash;
hash.insert(s);
while(fact--){
next_permutation(s.begin(),s.end());
hash.insert(s);
//cout<<s<<endl;
}
vector<string> ans;
for(auto c : Str){
if(c.size() == str.size() && c != str && hash.count(c)){
ans.push_back(c);
}
}
sort(ans.begin(),ans.end());
cout<<ans.size()<<endl;
if(ans.size() >= k){
cout<<ans[k - 1];
}
else cout<<"";
return 0;
}
评论区