题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
//交换两个string类型元素
void swap(string& s, string& t)
{
string c;
c = s;
s = t;
t = c;
}
int main()
{
int n, k;
cin >> n;
vector<string> s(n);//存储接下来要输入的n个字典单词
for (auto it = s.begin(); it < s.end(); ++it){
cin >> *it;
}
string t;
cin >> t >> k;
int sum_browords = 0;
vector<string> v;//存储兄弟单词
for (auto it = s.begin(); it < s.end(); ++it) {
auto jt = t.begin();
if (t.size() == (*it).size() && t != *it){//兄弟单词要求之一:单词长度一致且不完全相同
for (jt = t.begin(); jt < t.end(); ++jt){//遍历t的每一个字母
if (count(t.begin(), t.end(), *jt) != count((*it).begin(), (*it).end(), *jt)){
break;//该字母在t中的数量如果不等于在*it中的数量,则*it不是兄弟单词
}
}
if (jt == t.end()){//如果jt遍历到了最后一个字母,则说明*it是兄弟单词
sum_browords++;
v.push_back(*it);//将兄弟单词放进v中
}
}
}
cout << sum_browords << endl;
if (v.size() >= k){//如果兄弟单词数量大于等于k再进行冒泡排序操作
for (auto pt = v.begin(); pt < v.end() - 1; ++pt){
for (auto qt = v.end() - 1; qt > pt; --qt){
if (*(qt - 1) > *qt){
swap(*(qt - 1), *qt);
}
}
}
cout << v[k - 1] << endl;
}
return 0;
}
兄弟单词的要求:1.单词长度相等;2.单词不完全相同;3.单词中的每一个字母数量都相同。
逻辑上不复杂,使用了it、jt、pt、qt四个迭代器,it、jt的目的是遍历s中的每一个单词和单词中的每一个字母。
查看10道真题和解析
