华为笔试题:查找兄弟单词

输入描述:

 

先输入字典中单词的个数,再输入n个单词作为字典单词。
输入一个单词,查找其在字典中兄弟单词的个数
再输入数字n

输出描述:

 

根据输入,输出查找到的兄弟单词的个数

示例1

输入

3 abc bca cab abc 1

输出

2
bca
#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
    int n;//单词个数
    while (cin >> n) {
        vector<string> s;
        for (int i = 0; i < n; ++i) {
            string ss;
            cin >> ss;
            s.push_back(ss);
        }
        sort(s.begin(), s.end());
        string str;//待查询的单词
        int index;//第几个兄弟单词
        cin >> str;
        cin >> index;
        map<char, int> mi;
        for (int i = 0; i < str.size(); ++i) {
            mi[str[i]]++;
        }
        int num = 0;
        string ans = "";
        for (int i = 0; i < n; ++i) {
            map<char, int> m;
            if (s[i] != str) {
                for (int j = 0; j < s[i].size(); ++j) {
                    m[s[i][j]]++;
                }
//                map<char,int>::iterator it;
//                for (it = m.begin(); it != m.end() ; ++it) {
//                    cout << it->first << "->" << it->second << endl;
//                }
                if (m == mi) {
                    num++;
                    if (index == num) ans = s[i];
                }
            }
        }
        cout << num << endl;
        if(num >= index) cout << ans << endl;
        else cout << "" << endl;
    }
    return 0;
}
发布了34 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41111088/article/details/105187118