题解 | #查找兄弟单词#

查找兄弟单词

https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68

#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <set>
using namespace std;

void split(const string& strSource, vector<string>& res,
           const string& delimiter = " ") {
    size_t left = strSource.find_first_not_of(delimiter, 0);
    size_t right = strSource.find_first_of(delimiter, left);
    while (left != string::npos || right != string::npos) {
        res.emplace_back(strSource.substr(left, right - left));
        left = strSource.find_first_not_of(delimiter, right);
        right = strSource.find_first_of(delimiter, left);
    }
}

int main() {
    string str;
    while (getline(cin, str)) {
        vector<string> vec;
        split(str, vec);
        int number = atoi(vec.at(0).c_str());
        map<char, int> mapSource;
        string strSource = vec.at(number + 1);
        for (auto& it : strSource) {
            mapSource[it]++;
        }
        multiset<string> setStr;
        int lengSource = strSource.length();
        for (int i = 1; i <= number; i++) {
            if (vec.at(i).size() == lengSource && vec.at(i) != strSource) {
                map<char, int> mapTemp;
                for (auto& it : vec.at(i)) {
                    mapTemp[it]++;
                }
                if (mapTemp == mapSource) {
                    setStr.emplace(vec.at(i));
                }
            }
        }
        int setSize = setStr.size();
        cout << setSize << endl;
        int index = atoi(vec.at(number + 2).c_str()) - 1;
        if (0 <= index && index < setStr.size()) {
            int i = 0;
            for (auto& it : setStr) {
                if (i == index) {
                    cout << it << endl;
                    break;
                }
                i++;
            }
        }
    }
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务