题解 | 查找兄弟单词

查找兄弟单词

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

#include <functional>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
bool isBrother(const string&S,const string &T){
    if(S.size()!=T.size())return false;
    if(S==T)return false;
    int visitedS[10]={0};
    int visitedT[10]={0};
    int count=0;
    for(int i=0;i<S.size();i++){
        for(int j=0;j<T.size();j++){
            if(visitedS[i]==0&&visitedT[j]==0&& S[i]==T[j]){
                count++;
                visitedS[i]=1;
                visitedT[j]=1;
            }
            if(count==S.size())return true;
            
        }
    }
    return false;
}

int main() {
    int n;cin>>n;
    vector<string>s_box;
    while (n--) {
    string s;
    cin>>s;
    s_box.push_back(s);
    }
    string x;cin>>x;
    int k;cin>>k;
    priority_queue<string,vector<string>,greater<string>>que;
    for(string s:s_box){
        if(isBrother(s,x))que.push(s);
    }
    cout<<que.size()<<endl;
    if(que.size()!=0&&k<=que.size()){
    k--;
    while(k--)que.pop();
    cout<<que.top()<<endl;}
    
    
}
// 64 位输出请用 printf("%lld")

原始思路:优先队列排序,简单但开销大,就当练手了。

抄袭来的思路:用mutiset先排序,遍历的时候同时计数和寻找目标值。

#include <iostream>
#include <set>
#include <algorithm>

using namespace std;

bool isBrotherWord(string s1, string s2) {
    if (s1 == s2) {
        return false;
    }
    sort(s1.begin(), s1.end());
    sort(s2.begin(), s2.end());
    if (s1 == s2) {
        return true;
    } else {
        return false;
    }
}

int main() {
    int n;
    cin >> n;
    multiset<string> str_set;
    while(n > 0) {
        string s;
        cin >> s;
        str_set.insert(s);
        n--;
    }
    string x;
    cin >> x;
    int k;
    cin >> k;
    int count = 0;
    string res;
    for(auto s : str_set) {
        if (isBrotherWord(s, x)) {
            count++;
            k--;
            if (k == 0) {
                res = s; 
            }
        }
    }

    cout << count << endl;
    if (!res.empty()) {
        cout << res << endl;
    }

    return 0;
}

全部评论

相关推荐

包行:平时怎么刷算法题的哇,字节的手撕听说都很难
字节跳动工作体验
点赞 评论 收藏
分享
10-28 10:48
已编辑
门头沟学院 Java
孩子我想要offer:发笔试后还没笔试把我挂了,然后邮箱一直让我测评没测,后面不知道干嘛又给我捞起来下轮笔试,做完测评笔试又挂了😅
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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