思路:
利用map保存每个单词出现的次数,然后遍历,如果是兄弟单词,就统计下标,和总个数,最后输出结果。
题目描述
定义一个单词的“兄弟单词”为:交换该单词字母顺序,而不添加、删除、修改原有的字母就能生成的单词。
兄弟单词要求和原来的单词不同。例如:ab和ba是兄弟单词。ab和ab则不是兄弟单词。
现在给定你n个单词,另外再给你一个单词str,让你寻找str的兄弟单词里,字典序第k大的那个单词是什么?
注意:字典中可能有重复单词。本题含有多组输入数据。
Example:
#include<iostream>
#include<map>
using namespace std;
bool isBrother(string &a, string b)
{
if(a == b) return false;
map<char, int> AMap;
map<char, int> BMap;
for(auto x : a) AMap[x]++;
for(auto x : b) BMap[x]++;
if(AMap.size() != BMap.size()) return false;
for(auto x = AMap.begin(), y = BMap.begin(); x != AMap.end() && y != BMap.end(); x++, y++) {
if(x->first != y->first || x->second != y->second) return false;
}
return true;
}
int main()
{
int n;
while(cin >> n) {
map<string, int> s;
s.clear();
string word;
for(int i = 0; i < n; i++) {
cin >> word;
s[word]++;
}
cin >> word;
int dest, count = 0;
string res = "";
cin >> dest;
for(auto x : s) {
if(isBrother(word, x.first)) {
count += x.second;
dest -= x.second;
if(res == "" && dest <= 0) res = x.first;
}
}
cout << count << endl;
if(res != "") cout << res << endl;
}
}