priority_queue的用法

本文深入探讨了一种解决字符串重组问题的高效算法,该算法利用优先队列(大顶堆)来确保相邻字符不相同,同时提供了详细的代码实现与示例说明。

767. Reorganize String

Medium

51927FavoriteShare

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].
class Solution {
public:
    //--按照大顶堆建堆
    struct Cmp{
        bool operator()(const pair<int,char>& x,const pair<int,char>& y){
            return x.first < y.first;
        }
    };
    string reorganizeString(string S){
        unordered_map<char,int> HashMap;
    for(auto s : S){
        HashMap[s] ++;
    }
    priority_queue<pair<int,char>,vector<pair<int,char>>,Cmp> q;
    for(auto i = HashMap.begin();i != HashMap.end();i++){
        q.push(make_pair(i->second,i->first));
    }
    string Result;
    while(!q.empty()){
        if(q.size() == 1){
            pair<int,char> tmp = q.top();
            q.pop();
            Result.insert(Result.end(),tmp.first,tmp.second);
        }
        else{
            pair<int,char> First = q.top();
            q.pop();
            pair<int,char> Second = q.top();
            q.pop();
            if(First.first > 0){
                Result.push_back(First.second);
                First.first--;
                if(First.first > 0){
                    q.push(First);
                }
            }
            if(Second.first > 0){
                Result.push_back(Second.second);
                Second.first--;
                if(Second.first > 0){
                    q.push(Second);
                }
            }
        }
    }
    if(Result.length() >= 2 && Result[Result.length() - 1] == Result[Result.length() - 2]){
        Result = "";
    }
    return Result;
    }

};

 

priority_queue本质是一个堆。

1. 头文件是#include<queue>

2. 关于priority_queue中元素的比较

  模板申明带3个参数:priority_queue<Type, Container, Functional>,其中Type 为数据类型,Container为保存数据的容器,Functional 为元素比较方式。

  Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector。

2.1 比较方式默认用operator<,所以如果把后面2个参数缺省的话,优先队列就是大顶堆(降序),队头元素最大。

关于重载()的函数对象Cmp的相关用法请看以下链接:相关链接,注意大顶堆是默认比较的,运算符重载为operator<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值