题解 | 查找兄弟单词

查找兄弟单词

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

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

// 判断两个字符串是否是兄弟单词
bool IsBrother(const string& compare, const string& base) {
    if (compare.length() != base.length()) 
        return false; // 长度不同,直接返回 false
    if (compare == base) 
        return false; // 完全相同,不是兄弟单词

    // 统计 compare 和 base 中每个字符的出现次数
    vector<int> compareCount(26, 0);
    vector<int> baseCount(26, 0);
    for (char ch : compare) compareCount[ch - 'a']++;
    for (char ch : base) baseCount[ch - 'a']++;

    // 如果字符统计结果相同,则是兄弟单词
    return compareCount == baseCount;
}

int main() {
    int n;
    cin >> n;
    vector<string> words(n);
    for (int i = 0; i < n; i++) {
        cin >> words[i];
    }
    string x;
    cin >> x;
    int k;
    cin >> k;

    // 统计兄弟单词
    vector<string> brothers;
    for (const string& word : words) {
        if (IsBrother(word, x)) {
            brothers.push_back(word);
        }
    }

    // 输出兄弟单词的数量
    cout << brothers.size() << endl;

    // 如果存在兄弟单词且 k 有效,输出第 k 个兄弟单词
    if (!brothers.empty() && k <= brothers.size()) {
        sort(brothers.begin(), brothers.end()); // 按字典序排序
        cout << brothers[k - 1] << endl;
    }

    return 0;
}

这道题给我看得有点懵,题干说的是交换任意两个字母的位置,但给的示例1给人的感觉是可以交换很多次,也就意味着三个不同的字母排列组合的方式有6种,所以才会有5个兄弟单词,那就只好计算每个字母出现的次数洛。

全部评论

相关推荐

迷茫的大四🐶:💐孝子启动失败,改为启动咏鹅
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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