题解 | #查找兄弟单词#

查找兄弟单词

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

用multiset字典里的重复单词也能够捕捉到,判断兄弟单词,最开始我想到的是排列组合,但是这样不好比对,参考了一下大佬的代码,发现判断兄弟单词,可以通过长度,单词的字符集是否完全相同来判断,那么这就衍生了两个方法,首先对字典遍历,遍历的单词要么hash一下看是否和原来的单词的字符集是一样的,要么两个单词排序一下,看是否相等。

#include <string>
#include <map>
#include <vector>
#include <set>
#include <algorithm>


using namespace std;

bool isbrother(string s1,string s2)
{
    if(s1.size()==s2.size()){
        if(s1==s2) return false;
        else {sort(s1.begin(),s1.end());
              sort(s2.begin(),s2.end());
              if(s1==s2) return true;
              else return false;
              
             }
        }//最外层if
    else return false;
    }

int main() {
    unsigned N;
    unsigned K;
    string str,wtfind;//want to find
    vector<string> word;
    multiset<string> brother;//插入的兄弟单词已经按字典序排好了
    cin>>N;
    unsigned size=0;
    while(N){
        cin>>str;
        word.push_back(str);
        N--;
        
    }//while
    cin>>wtfind;
    cin>>K;
    for(unsigned i = 0;i<word.size();i++){
        if(isbrother(wtfind,word[i])){
            
            brother.insert(word[i]);
        }
    }//for
    size = brother.size();
    cout<<size<<endl;
    if(size>=K){
        auto it = brother.begin();
        while(K){
            ++it;
            --K;
        }
        cout<<*(--it)<<endl;
    }
    
    
    
    
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-27 18:00
点赞 评论 收藏
分享
程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
每晚夜里独自颤抖:要求太多的没必要理
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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