HJ 27 Find Brother Words

Ideas:

Use map to save the number of occurrences of each word, and then traverse. If it is a sibling word, count the subscript and the total number, and finally output the result.

Title description

The "brother word" of a word is defined as a word that can be generated by swapping the letter order of the word without adding, deleting, or modifying the original letters.

The sibling word requirements are different from the original words. For example: ab and ba are brother words. ab and ab are not brother words.

Now given you n words, another word str is given to you to find the k-th largest word in the lexicographical order among the sibling words of str?

Note: There may be repeated words in the dictionary. This question contains multiple sets of input data.

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;
    }
}

 

Guess you like

Origin blog.csdn.net/u012571715/article/details/114969804