华为OD机试 - 字符串重新排序

// 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值