题解 | #查找兄弟单词#

查找兄弟单词

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

#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <algorithm>

using namespace std;

struct Word {
    std::string raw; // 原始字符串
    std::string sorted; // 按字典序排序后的
};

int main() {
    int n = 0;
    int k = 0;
    std::string base;
    std::vector<Word> dict;

    // 读取字典条目个数
    cin >> n;
    dict.resize(n);

    // 读取字典条目
    for (int i = 0; i < n; i++) {
        cin >> dict[i].raw;
        dict[i].sorted = dict[i].raw;
    }

    // 读取基准单词
    cin >> base;

    cin >> k;

    // 将字典条目按照字典序排列, 便于后续比较是否为兄弟单词
    for (auto& item : dict) {
        sort(item.sorted.begin(), item.sorted.end());
    }

    std::string base_sorted = base;
    sort(base_sorted.begin(), base_sorted.end());

    std::vector<std::string> brother;
    for (const auto& item : dict) {
        if (base == item.raw) {
            continue;
        }
        if (base_sorted == item.sorted) {
            brother.push_back(item.raw);
        }
    }

    sort(brother.begin(), brother.end());
    int i = 1;
    std::string ret;
    for (auto it = brother.begin(); it != brother.end(); it++) {
        if (i == k) {
            ret = *it;
            break;
        }
        i++;
    }

    std::cout << brother.size() << std::endl;
    std::cout << ret << std::endl;

    return 0;
}

全部评论

相关推荐

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