题解 | #查找兄弟单词#

查找兄弟单词

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

//就是按要求来,先把兄弟单词找到存起来(长度相同且不完全相等,同时每个字母的统计数量相同)
//字典序用冒泡把兄弟单词进行从小到大排序
//调试时间花在写stringsort函数(只有当前char相同才往后,不然就要return了)、最后的brother数据可能为空、cin的数据格式要正确

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

int stringsort(string str1,string str2){
    int minlen = min(str1.size(),str2.size());
    for(int i = 0;i<minlen;++i){
        if((str1[i]-str2[i])==0)continue;
        else if((str1[i]-str2[i])>0)return 1;
        else return 0;
    }
    return 0;
}

int main(){
    int n;
    cin >> n;
    vector<string> words;
    for(int i = 0;i<n;++i){
        string tmpval;
        cin >> tmpval;
        words.emplace_back(tmpval);
    }
    string strx;
    cin >> strx;
    vector<int> strxarr(26,0);
    for(int i = 0;i<strx.size();++i){
        strxarr[strx[i]-'a'] += 1;
    }
    int k;
    cin >> k;
    //先找兄弟单词,然后记录
    vector<string> brotherwords;
    for(int i = 0;i<n;++i){
        if(words[i].size() != strx.size() || words[i] == strx)continue;
        vector<int>wordsarr(26,0);
        for(int j = 0;j<words[i].size();++j){
            ++wordsarr[words[i][j]-'a'];
        }
        int record = 1;
        for(int j = 0;j<26;++j){
            if(wordsarr[j] != strxarr[j]){
                record = -1;
                break;
            }
        }
        if(record == 1)brotherwords.emplace_back(words[i]);
    }
    cout << brotherwords.size() << endl;
    //按字典序排列,冒泡排
    for(int i = 0;i<brotherwords.size();++i){
        for(int j = i+1;j<brotherwords.size();++j){
            //判断brotherwords的i是否大于brotherwords的j,大就交换
            if(stringsort(brotherwords[i],brotherwords[j]) == 1){
                string tmp = brotherwords[i];
                brotherwords[i] = brotherwords[j];
                brotherwords[j] = tmp;
            }
        }
    }
    if(brotherwords.size() > 0)cout << brotherwords[k-1] << endl;
    return 0;
}
全部评论

相关推荐

巨人网络 测试 总包20左右
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务