[leetcode]767. Reorganize String

162 篇文章 0 订阅
23 篇文章 0 订阅

[leetcode]767. Reorganize String


Analysis

holy shit—— [每天刷题并不难0.0]

Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

If possible, output any possible result. If not possible, return the empty string.
在这里插入图片描述

Explanation:

先把字符串按照字母出现的次数降序排序

Implement

solution 1:(priority queue)

class Solution {
public:
    string reorganizeString(string S) {
        int len = S.size();
        vector<int> cnt(26);
        for(char c:S)
            cnt[c-'a']++;
        priority_queue<pair<int, char>> pq;
        for(int i=0; i<26; i++){
            if(cnt[i] > (len+1)/2)
                return "";
            if(cnt[i])
                pq.push({cnt[i], i+'a'});
        }
        queue<pair<int, char>> q;
        string res = "";
        while(!pq.empty() || q.size()>1){
            if(q.size()>1){
                auto cur = q.front();
                q.pop();
                if(cur.first != 0)
                    pq.push(cur);
            }
            if(!pq.empty()){
                auto cur = pq.top();
                pq.pop();
                res += cur.second;
                cur.first--;
                q.push(cur);
            }
        }
        return res;
    }
};

solution 2:(sort by occurrence)

class Solution {
public:
    string reorganizeString(string S) {
        int len = S.size();
        vector<int> cnt(26);
        for(char c:S)
            cnt[c-'a']++;
        vector<pair<int, char>> cnt1;
        for(int i=0; i<26; i++){
            if(cnt[i] > (len+1)/2)
                return "";
            if(cnt[i])
                cnt1.push_back({cnt[i], i+'a'});
        }
        sort(cnt1.rbegin(), cnt1.rend());
        string res = "";
        string str = "";
        for(auto& p:cnt1){
            for(int i=0; i<p.first; i++)
                str += p.second;
        }
        for(int i=0,j=(len-1)/2+1; i<(len-1)/2+1; i++,j++){
            res += str[i];
            if(j < len)
                res += str[j];
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值