LeetCode767. 重构字符串

767. Reorganize String

[Medium] 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.

Example 1:

Input: S = "aab"
Output: "aba"

Example 2:

Input: S = "aaab"
Output: ""

Note:

  • S will consist of lowercase letters and have length in range [1, 500].

题目:给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。若可行,输出任意可行的结果。若不可行,返回空字符串。

思路:按照字符的频率构建优先队列。每次优先考虑添加频率最高的字符,如果冲突,则考虑添加频率次高的字符。

工程代码下载 Github

class Solution {
public:
    string reorganizeString(string S) {
        int arr[26] = {0};
        for(auto c : S)
            arr[c-'a'] += 1;

        priority_queue<pair<int, char>, vector<pair<int, char>>> pq;
        for(int i = 0; i < 26; ++i){
            if(arr[i] > (S.size()+1)/2)
                return "";
            if(arr[i] > 0)
                pq.push({arr[i], 'a'+i});
        }

        string res;
        while(!pq.empty()){
            pair<int, char> p1 = pq.top();
            pq.pop();

            if(res.empty() || res.back() != p1.second){
                res += p1.second;
                if(p1.first > 1)
                    pq.push({p1.first-1, p1.second});
            }
            else{
                // 如果队列当前最高频的字符 与 结果字符串的最后一个字符相同
                // 则考虑添加次高频的字符
                if(pq.empty())
                    return "";
                pair<int, char> p2 = pq.top();
                pq.pop();
                res += p2.second;
                if(p2.first > 1)
                    pq.push({p2.first-1, p2.second});
                pq.push(p1);
            }
        }

        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值