题解 | 查找兄弟单词

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

int main() {
    int n;
    cin >> n;
    vector<string> words;
    while (n --) { // 注意 while 处理多个 case
        string word;
        cin >> word;
        words.push_back(word);
    }

    string target;
    cin >> target;
    int idx;
    cin >> idx;

    vector<string> result;
    for (auto & word : words) {
        // 长度不相等,不是兄弟单词
        if (word.size() != target.size()) {
            continue;
        }

        // 内容完全一样,不是兄弟单词
        if (word == target) {
            continue;
        }

        // 在满足 单词长度一样,且内容不同的时候
        // 统计单词中每个字符的数量
        map<char, int> m1, m2;
        for (int j = 0; j < target.size(); j++) {
            m1[word[j]] ++;
            m2[target[j]] ++;
        }

        // 如果相同字符的数量一样,认为是兄弟单词
        bool isright = true;
        for (char & j : target) {
            if (m1[j] != m2[j]) {
                isright = false;
                break;
            }
        }
        if (isright) {
            result.push_back(word);
        }

    }
    
    // 按字典序排序
    sort(result.begin(), result.end());
    if (result.size() != 0) {
        cout << result.size() << endl;
        cout << result[idx - 1] << endl;
    } else {
        cout << '0' << endl;
    }

    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务