题解 | #查找兄弟单词#
查找兄弟单词
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;
}
}
查看11道真题和解析
