题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
#include <algorithm> #include <cmath> #include <cstring> #include <iostream> #include <sstream> #include <vector> #include <map> using namespace std; bool isbro(string to_exam, map<char, int> bro) { map<char, int> tem_set; for (auto x : to_exam) { if (tem_set.find(x) == tem_set.end()) { tem_set.insert({x, 1}); } else { tem_set[x]++; } } if(tem_set.size()!=bro.size()){ return false; } int match_count = 0; for(auto x:tem_set){ if(x.second==bro[x.first]){ match_count++; } } if(match_count == bro.size()){ return true; } return false; } int main() { map<char, int> to_exam; vector<string> bro_list; int num; string s; getline(cin, s); istringstream ns(s); ns>>num; int k = 0; int digit = 0; for(int i = s.size()-1;i>=0;i--){ if(s[i]>='0'&&s[i]<='9'){ k+=(s[i]-'0')*pow(10,digit); digit++; }else{ break; } } string to_find; int flag = 0; for (int i = s.size() - 2; i >= 0; i--) { if (s[i] == ' ') { if (flag == 0) { flag = 1; continue; } else { break; } } else { to_find += s[i]; } } reverse(to_find.begin(), to_find.end()); for (auto x : to_find) { if (to_exam.find(x) == to_exam.end()) { to_exam.insert({x, 1}); } else { to_exam[x]++; } } stringstream ss(s); string tem; while(ss>>tem){ if(tem == to_find){ continue; }else{ //cout<<"*"<<to_exam.size()<<endl; if(isbro(tem,to_exam)){ //cout<<tem<<endl; bro_list.push_back(tem); } } } sort(bro_list.begin(),bro_list.end()); if(k>bro_list.size()){ cout<<bro_list.size(); }else{ cout<<bro_list.size()<<endl<<bro_list[k-1]; } }