题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
#include <iostream>
#include <string>
#include <deque>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::deque;
using std::sort;
// 判断两个字符串是否构成“兄弟字符串”
bool is_brothers_two_words(const string& lhs, const string& rhs) {
if (lhs.size() != rhs.size()) {
return false;
}
if (lhs != rhs) {
string sorted_lhs = lhs;
string sorted_rhs = rhs;
sort(sorted_lhs.begin(), sorted_lhs.end());
sort(sorted_rhs.begin(), sorted_rhs.end());
// 检查排序后的字符串是否相等
return sorted_lhs == sorted_rhs;
} else {
return false;
}
}
void test() {
deque<string> vec;
deque<string> vec1;
int n; // 字符串的数量
cin >> n;
for (int i = 0; i < n; i++) {
string str;
cin >> str;
vec.push_back(str);
}
sort(vec.begin(), vec.end());
string target;
cin >> target;
int count = 0;
for (const auto& str : vec) {
if (is_brothers_two_words(str, target)) {
count++;
vec1.push_back(str);
}
}
int k;
cin >> k;
cout << count << endl;
if (k > 0 && k <= vec.size()) {
cout << vec1[k - 1] << endl;
} else {
cout << "Invalid index" << endl;
}
}
int main() {
test();
return 0;
}