题解 | #查找兄弟单词#
查找兄弟单词
http://www.nowcoder.com/questionTerminal/03ba8aeeef73400ca7a37a5f3370fe68
大概有2个注意点。
1.与目标字符串完全相同的字符串不属于兄弟单词。
2.要对兄弟字符串数组进行字典序排序
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<math.h>
#include<set>
using namespace std;
bool cmp(const string &str1,const string &str2)
{
int num = min(str1.size(),str2.size());
for(int i = 0;i < num;i++)
{
if(str1[i] != str2[i])
{
return str1[i] < str2[i];
}
}
return str1.size() < str2.size();
}
bool isBrother(string &str,string &target)
{
if(str.size() != target.size())
{
return false;
}
if(str == target)
{
return false;
}
vector<char>tmp1;
vector<char>tmp2;
tmp1.assign(str.begin(),str.end());
tmp2.assign(target.begin(),target.end());
sort(tmp1.begin(),tmp1.end());
sort(tmp2.begin(),tmp2.end());
for(int i = 0;i < tmp1.size();i++)
{
if(tmp1[i] != tmp2[i])
{
return false;
}
}
return true;
}
int main()
{
int num;
while(cin >> num)
{
vector<string>strs(num);
for(int i = 0;i < num;i++)
{
cin >> strs[i];
}
string target;
cin >> target;
vector<string>brother;
for(int j = 0;j < num;j++)
{
if(isBrother(strs[j],target))
{
brother.push_back(strs[j]);
}
}
int k;
cin >> k;
cout << brother.size() << endl;
if(k > brother.size())
{
continue;
}
sort(brother.begin(),brother.end(),cmp);
cout << brother[k - 1] << endl;
}
return 0;
}