题解 | #查找兄弟单词#

查找兄弟单词

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

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;
bool isSibWords(string& str1, string&str2);

int main() {
    int cnt =0;
    string temp;
    string wordx;
    int k = 0;
    vector<string> dicvec;
    vector<string> sibvec;
    
    cin >> cnt;
    for(int i=0; i<cnt; i++)
    {
        cin >> temp;
        dicvec.push_back(temp);
    }
    cin >> wordx;
    cin >> k;
    for(int i=0;i<cnt;i++)
    {
        if(isSibWords(dicvec[i], wordx))
        {
            sibvec.push_back(dicvec[i]);
        }
    }
    cout << sibvec.size() <<endl;
    //对sibvec进行排序
    sort(sibvec.begin(), sibvec.end());
    if(k >= 0 && k<sibvec.size())
    {
        cout <<sibvec[k-1] <<endl;
    }

    return 0;
}

//数据结构:定义一个兄弟单词的容器,vector<string>
//当发现是兄弟单词,加入这个容器中。
//然后对这个容器按照字典序进行排序。
//求排序后的第k个单词,首先要判断k的合法性
//如果k 不合法,那么,就不要输出
bool isSibWords(string& str1, string&str2)
{
    if(str1 == str2)
    {
        return false;
    }
    int len1 = str1.size();
    int len2 = str2.size();
    if(len1 != len2) return false;

    int hash1[127] = {0};
    int hash2[127] = {0};

    for(int i=0; i<len1;i++)
    {
        hash1[str1[i]]++;
    }
    for(int i=0; i<len2;i++)
    {
        hash2[str2[i]]++;
    }
    int idx=0;
    for( ;idx<127;idx++)
    {
        if(hash1[idx]!= hash2[idx])
        {break;}
    }
    if(idx == 127)
    {
        return true;
    }else {
        return false;
    }

}

全部评论

相关推荐

09-08 17:17
同济大学 Java
狗不理fe:里面的人劝一句,别来虾,我们部门24校招生淘汰率30%,还有一些人说有一年保护期,不可能!!!
我的秋招日记
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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