[leetcode]767. Reorganize String

[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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/86712982