牛客NC222104重排字符串(C++)

题目链接
在这里插入图片描述
在这里插入图片描述
实现方法

  1. 统计各字符出现的次数;
  2. 判断是否能实现重排(根据出现次数最多的字符数量ma和字符总长度n判断);
  3. 依次输出出现次数最多的两个字符,直到出现次数最多的字符和次多的字符数量相同;
  4. 依次输出剩余的所有字符;

代码

#include <bits/stdc++.h>
using namespace std;

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
	//ma记录出现次数最多字符的数量
    int n,ma=0;
    string ss;
    cin>>n>>ss;
    map<char,int>m;
    for(auto i:ss){
        m[i]++;
    }
    //使用multiset存放各字母与其出现的次数,可始终保持出现次数最多的字符在末尾,便于取出
    multiset<pair<int,char>>s;
    for(auto i:m){
        ma=max(ma,i.second);
        s.insert({i.second,i.first});
    }
    //判断是否有可行解
    //n为偶数时:n/2<ma无解
    //n为奇数时:n/2-1>ma无解
    if(2*ma-1>n)return cout<<"no",0;
    cout<<"yes"<<endl;
   //记录当前循环输出的最后一个字符,防止与下一步输出的第一个字符相同
    char c;
    while(n>0){
    	//取出数量最多的两个元素
        auto temp=*s.rbegin();
        s.erase(temp);
        auto temp2=*s.rbegin();
        s.erase(temp2);
        if(temp.first!=temp2.first){
            cout<<temp.second;
            temp.first--;
            if(temp.first){
                cout<<temp2.second;
                c=temp2.second;
                temp2.first--;
            }
            else break;
            s.insert(temp);
            s.insert(temp2);
        }
        //当出现次数最多和第二多的字符数相同时跳出循环
        else{
            s.insert(temp);
            s.insert(temp2);
            break;
        }
        n--;
    }
    vector<pair<int,char>>v;
    for(auto i:s){
        v.push_back(i);
    }
    //防止第一个输出的元素与上一个循环输出的最后一个元素相同
    if(v.back().second==c){
        swap(v.back(),v.front());
    }
    while(1){
    	//判断该次循环是否输出字符,若没有输出表示已完成所有字符的输出,结束循环。
        int jud=0;
        //依次输出剩余元素
        for(int i=v.size()-1;i>=0;i--){
            if(v[i].first){
                cout<<v[i].second;
                v[i].first--;
                jud=1;
            }
        }
        if(!jud)break;
    }
    return 0;
}

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值