题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main(void)
{
int ans = 0;
vector<string> words;
int n;
cin >> n;
vector<string> strs(n);
string target;
int k;
for (int i = 0; i < n; i++)
{
cin >> strs[i];
}
cin >> target >> k;
string tmp1 = target;
sort(tmp1.begin(),tmp1.end());
for (int i = 0; i < n; i++)
{
//不满足兄弟单词的规则就跳过
if (strs[i].size() != target.size() || strs[i] == target)
{
continue;
}
string tmp = strs[i];
sort(tmp.begin(),tmp.end());
if (tmp == tmp1)
{
ans++;//更新兄弟单词个数
words.push_back(strs[i]);//更新兄弟单词
}
}
sort(words.begin(),words.end());//按字典排序兄弟单词
cout << ans << endl;
if (!words.empty() && k < words.size())//防止越界
{
cout << words[k-1] << endl;
}
return 0;
}
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main(void)
{
int ans = 0;
vector<string> words;
int n;
cin >> n;
vector<string> strs(n);
string target;
int k;
for (int i = 0; i < n; i++)
{
cin >> strs[i];
}
cin >> target >> k;
string tmp1 = target;
sort(tmp1.begin(),tmp1.end());
for (int i = 0; i < n; i++)
{
//不满足兄弟单词的规则就跳过
if (strs[i].size() != target.size() || strs[i] == target)
{
continue;
}
string tmp = strs[i];
sort(tmp.begin(),tmp.end());
if (tmp == tmp1)
{
ans++;//更新兄弟单词个数
words.push_back(strs[i]);//更新兄弟单词
}
}
sort(words.begin(),words.end());//按字典排序兄弟单词
cout << ans << endl;
if (!words.empty() && k < words.size())//防止越界
{
cout << words[k-1] << endl;
}
return 0;
}
查看15道真题和解析
联想公司福利 1523人发布