// Online C++ compiler to run C++ program online
#include<iostream>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<string>
#include<exception>
#include<map>
using namespace std;
bool comp(pair<string, int> a, pair<string, int> b) {
//次数降序、长度升序、字典序排列升序
if (a.second > b.second)
{
return true;
}
else if (a.second == b.second)
{
if (a.first.size() > b.first.size())
{
return false;
}
else if (a.first.size() == b.first.size())
{
return a.first < b.first;
}
return true;
}
return false;
}
int main() {
string str;
getline(cin, str);
vector<string> list;
while (str.find(" ") != string::npos)
{
int found = str.find(" ");
list.emplace_back(str.substr(0, found));
str = str.substr(found + 1);
}
list.emplace_back(str);
//第一步,单词内部调整
//第二步,单词间调整
//先统计每个单词出现的次数
map<string, int> str_count;
for (auto& token : list)
{
sort(token.begin(), token.end());
if (str_count.count(token))
{
str_count[token] += 1;
}
else
{
str_count[token] = 1;
}
}
// 排序
vector<pair<string, int>> pairList;
for (auto x : str_count) {
pairList.push_back(x);
}
sort(pairList.begin(), pairList.end(), comp);
for (auto token : pairList) {
for (int i = 0; i < token.second; ++i)
{
cout << token.first << " ";
}
}
return 0;
}
华为OD机试 - 字符串重新排序
最新推荐文章于 2024-10-19 15:29:34 发布