LeetCode 767.文字列のリファクタリング(スペルに関する消費の考え方)

題名:

给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。

若可行,输出任意可行的结果。若不可行,返回空字符串。

数据范围:
S 只包含小写字母并且长度在[1, 500]区间内。

解決:

依据对拼消耗思想,当出现次数最多的字符的数量cnt>(n+1)/2,那么无解,
可以看作每次取出一个数量最大的,然后选出另外一个对拼消耗,
最劣情况下是出现次数最多的字符的数量cnt=(n+1)/2,
超过这个范围就无解了.


否则一定有解,考虑如何构造解:

做法1:
大顶堆存所有(数量,字符)二元组,
每次取出堆顶的两个,接到答案串后面即可.

code1:

//大顶堆
#define PI pair<int,char>
class Solution {
    
    
public:
    string reorganizeString(string s) {
    
    
        map<char,int>mp;
        int n=s.size();
        int ma=0;
        for(int i=0;i<n;i++){
    
    
            mp[s[i]]++;
            ma=max(ma,mp[s[i]]);
        }
        priority_queue<PI,vector<PI>, less<PI> >q;
        for(auto i:mp){
    
    
            q.push({
    
    i.second,i.first});
        }
        string ans;
        while(q.size()){
    
    
            PI x=q.top();q.pop();
            if(!q.size()){
    
    
                if(x.first>1)return "";//无解
                ans+=x.second;
                break;
            }
            PI y=q.top();q.pop();
            ans+=x.second;
            ans+=y.second;
            x.first--;
            y.first--;
            if(x.first)q.push(x);
            if(y.first)q.push(y);
        }
        return ans;
    }
};

おすすめ

転載: blog.csdn.net/weixin_44178736/article/details/114006786