一、题目
二、解题思路
1、先对每个单词内部进行排序,再对单词间进行排序
2、使用map,key为单词,value为出现的次数
3、由于要对map排序,构造pair型的一维数组,将map的key、value放进去
4、构造函数,按照次数降序、长度升序、字典升序进行排序
三、代码
#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
vector<string>split(string params) {
vector<string>p;
while (params.find(" ") != string::npos) {
int found = params.find(" ");
p.push_back(params.substr(0, found));
params = params.substr(found + 1);
}
p.push_back(params);
return p;
}
bool comp(pair<string, int>a, pair<string, int>b) {
//次数降序、长度升序、字典升序
if (a.second > b.second) {
return a.second > b.second; //出现次数降序
}
else if (a.second == b.second) {
if (a.first.size() > b.first.size()) {
return a.first.size() < b.first.size(); //次数相同,则长度升序
}
else if (a.first.size() == b.first.size()) {
return a.first < b.first; //次数、长度相同,则字典升序
}
else {
return a.first.size() < b.first.size(); //长度升序
}
}
else {
return a.second > b.second; //出现次数降序
}
}
int main() {
string input_str;
getline(cin, input_str);
vector<string>v = split(input_str);
//第一步:单词内部调整
for (int i = 0; i < v.size(); i++) {
sort(v[i].begin(), v[i].end()); //对数组每一个元素即单词进行排序
}
//第二步:单词间调整
//先统计每个单词出现的次数
map<string, int>str_count_map; //key为单词,value为出现的次数
for (int i = 0; i < v.size(); i++) { //遍历数组每一个单词
if (str_count_map.count(v[i])) {
str_count_map[v[i]]++;
}
else {
str_count_map[v[i]] = 1;
}
}
//排序
vector<pair<string, int>>str_count_vec; //注意使用了pair
for (auto x : str_count_map) { //遍历map的元素
str_count_vec.push_back(make_pair(x.first, x.second)); //将map的key、value放进数组
}
sort(str_count_vec.begin(), str_count_vec.end(), comp); //结合自定义的comp对数组,根据出现的次数、长度、字典进行排序
for (int i = 0; i < str_count_vec.size(); i++) { //由于map导出的数组的key是不重复的,所以不能直接输出,而要在第二次for循环利用map的value输出重复出现的key
for (int j = 0; j < str_count_map[str_count_vec[i].first]; j++) {
cout << str_count_vec[i].first << " ";
}
}
return 0;
}