题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
创建一个map用于统计原字符串中每个字母出现的次数,再创建一个map依次统计序列中每个字符串的每个字母出现次数,如果两个字符串长度相等并且每个字母出现的次数相等,且两个字符串不相等,即为兄弟字符串,将其添加到vector中,排序后输出第k个字符串。
#include <iostream> #include <vector> #include <map> #include <algorithm> using namespace std; int main() { string s; int n; cin >> n; int order; vector<string> words; vector<string> brothers; map<char, int> letters; map<char, int> temp; for (int i = 0; i < n; i++) { cin >> s; words.push_back(s); } cin >> s; cin >> order; for (char letter : s) { if (letters.find(letter) != letters.end()) { letters[letter]++; } else { letters.insert({letter, 1}); } } for (string word : words) { bool flag = true; temp.clear(); for (char letter : word) { if (temp.find(letter) != temp.end()) { temp[letter]++; } else { temp.insert({letter, 1}); } } if (temp.size() == letters.size()) { for (pair<char, int> element : letters) { if (temp.find(element.first) == temp.end()) { flag = false; } else { if (temp[element.first] != element.second) { flag = false; } } } if (flag && word != s) { brothers.push_back(word); } } } sort(brothers.begin(), brothers.end()); cout << brothers.size() << endl; if (order <= brothers.size()) { cout << brothers.at(order - 1); } } // 64 位输出请用 printf("%lld")
中等(算法题解) 文章被收录于专栏
中等难度题目