题目描述
输入描述:
先输入字典中单词的个数,再输入n个单词作为字典单词。
输入一个单词,查找其在字典中兄弟单词的个数
再输入数字n
输出描述:
根据输入,输出查找到的兄弟单词的个数
示例1
输入
3 abc bca cab abc 1
输出
2 bca
代码1:
//第二十七题 查找兄弟单词
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int num_word;
while (cin >> num_word)
{
vector<string>vWord;
for (int i = 0; i < num_word; i++)
{
string temp;
cin >> temp;
vWord.push_back(temp);
}
sort(vWord.begin(), vWord.end());
int num;
string strFind;
cin >> strFind >> num;
vector<string>hStr;
int nLength = strFind.length();
int pSize[26]{ 0 };
for (int i = 0; i < nLength; i++)
{
pSize[strFind[i] - 'a']++;
}
for (int i = 0; i < num_word; i++)
{
int tLength = vWord[i].length();
if (nLength != tLength || vWord[i] == strFind)
{
continue;
}
else
{
int k = 0;
int nSize2[26]{ 0 };
for (; k < nLength; k++)
{
nSize2[vWord[i][k] - 'a']++;
}
for (k = 0; k < 26; k++)
{
if (pSize[k] != nSize2[k])
{
break;
}
}
if (k == 26 && strFind!= vWord[i])
{
hStr.push_back(vWord[i]);
}
}
}
int nFind = hStr.size();
cout << nFind <<endl;
if(nFind >= num)
cout << hStr[num - 1]<<endl;
}
return 0;
}
代码2:不是本人写的
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
bool isBrother(string str, string s)
{
if(str.size() == s.size())
{
if(str == s)
return false;
sort(str.begin(), str.end());
sort(s.begin(), s.end());
if(str == s)
return true;
}
return false;
}
int main()
{
int num;
while(cin >> num)
{
string str;
string word,s;
int index;
vector<string> vs;
for(int i = 0; i < num; ++i)
{
cin >> str;
vs.push_back(str);
}
sort(vs.begin(), vs.end()); // 因为是字典,一定要排序!!
cin >> word;
cin >> index;
int counts = 0;
for(int i = 0; i < num; ++i)
{
if(isBrother(word, vs[i]))
{
counts ++;
if(counts == index)
s = vs[i];
}
}
if(!vs.empty())
cout << counts << endl;
if(counts >= index)
cout << s << endl;
}
return 0;
}