Leetcode 767. Reorganize String

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Reorganize String

2. Solution

class Solution {
public:
    string reorganizeString(string S) {
    	int length = S.size();
    	int maximum = 0;
        map<char, int> m;
        for(char ch : S) {
        	m[ch]++;
        	maximum = max(maximum, m[ch]);
        }
        if(length - maximum < maximum - 1) {
        	return "";
        }
        priority_queue<pair<int, char>> pq;
        for(auto item : m) {
        	pq.push(make_pair(item.second, item.first));
        }
        string result = "";
        while(!pq.empty()) {
        	pair<int, char> p1 = pq.top();
        	pq.pop();
        	result += p1.second;
        	p1.first--;
        	if(!pq.empty()) {
        		pair<int, char> p2 = pq.top();
        		pq.pop();
               	result += p2.second;
        		p2.first--;
        		if(p2.first) {
        			pq.push(p2);
        		}
        	}
        	if(p1.first) {
        		pq.push(p1);
        	}

        }
        return result;
    }
};

Reference

  1. https://leetcode.com/problems/reorganize-string/description/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值