767. Reorganize String

767. Reorganize String


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

方法0: priority_queue

思路:

按照词频排序,统计出最高词频mx,每次pop队首元素round robin 放到mx个string中,最后将所有mx个string连接起来。

class Solution {
public:
    string reorganizeString(string S) {
        vector<int> count(26, 0);
        for (char c: S) count[c - 'a']++;
        int mx = *max_element(count.begin(), count.end());
        if (2 * mx > S.size() + 1) return "";
        priority_queue<pair<int, char>> pq;
        for (int i = 0; i < 26; i++) pq.push({count[i], i + 'a'});
        
        vector<string> tmp(mx, "");
        int n = 0;
        while (!pq.empty()){
            auto top = pq.top();
            pq.pop();
            for (int j = 0; j < top.first; j++) {
                tmp[(n++) % mx] += top.second;
            }
        }
        string result;
        for (string a: tmp) result += a;
        return result;
    }
};

方法1:

grandyang: https://www.cnblogs.com/grandyang/p/8799483.html

思路:

统计词频和排序的方法基本一致,但是在重构string 的时候,采用了不一样的方式。每一次从pq里pop出两个最高频的字母,将两个交叉累加到之前的结果中。如果在cnt-1后仍然还剩余字母,再将这个字母送回pq。这样就保证了每一次追加的高频字母之间是不发生重叠的。pq最后也可能出现只剩一个字母的情况,这个时候直接累加即可。因为提前判断了majority 不能多余 (size + 1) / 2 的情况,最后不用担心重叠。

class Solution {
public:
    string reorganizeString(string S) {
        string res = "";
        unordered_map<char, int> m;
        priority_queue<pair<int, char>> q;
        for (char c : S) ++m[c];
        for (auto a : m) {
            if (a.second > (S.size() + 1) / 2) return "";
            q.push({a.second, a.first});
        }
        while (q.size() >= 2) {
            auto t1 = q.top(); q.pop();
            auto t2 = q.top(); q.pop();
            res.push_back(t1.second);
            res.push_back(t2.second);
            if (--t1.first > 0) q.push(t1);
            if (--t2.first > 0) q.push(t2);
        }
        if (q.size() > 0) res.push_back(q.top().second);
        return res;
    }
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值