查找兄弟单词 查找兄弟单词

定义一个单词的“兄弟单词”为:交换该单词字母顺序(注:可以交换任意次),而不添加、删除、修改原有的字母就能生成的单词。
兄弟单词要求和原来的单词不同。例如: ab 和 ba 是兄弟单词。 ab 和 ab 则不是兄弟单词。
现在给定你 n 个单词,另外再给你一个单词 str ,让你寻找 str 的兄弟单词里,按字典序排列后的第 k 个单词是什么?
注意:字典中可能有重复单词。本题含有多组输入数据。

img


//调试了很久,通过50%,因为忽视了一个关键点,字典元素一定要排序
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
bool isBrother(string str, string s){    
    if(str.size() == s.size()){
        if(str == s)
            return false;
        sort(str.begin(), str.end());
        sort(s.begin(), s.end());
        if(str == s)
            return true;
    }
    return false;
}
int main(){
    int num;
    while(cin >> num){
        string str;
        string word,s;
        int index;
        vector<string> vs;
        for(int i = 0; i < num; ++i){
            cin >> str;
            vs.push_back(str);
        }  
        sort(vs.begin(), vs.end());  // 因为是字典,一定要排序!!
        cin >> word;
        cin >> index;
        int counts = 0;
        
        for(int i = 0; i < num; ++i){
            if(isBrother(word, vs[i])){
                counts ++;
                if(counts == index)
                    s = vs[i];
            }
        } 
        if(!vs.empty())
            cout << counts << endl;
        if(counts >= index)
            cout << s << endl;  
       
    }
    return 0;
}