Leetcode 767:重构字符串

∥☆過路亽.° 提交于 2019-12-11 02:10:09

题目描述

给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。

若可行,输出任意可行的结果。若不可行,返回空字符串。

示例 1:

输入: S = "aab"
输出: "aba"
示例 2:

输入: S = "aaab"
输出: ""
注意:

S 只包含小写字母并且长度在[1, 500]区间内。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorganize-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 

解题思路

struct cmp{
    bool operator()(pair<char,int> a,pair<char,int> b){
        return a.second<b.second;
    }
};
class Solution {
public:
    string reorganizeString(string S) {
        string ans = "";
        char pre=' ';
        unordered_map<char,int> mp;
        stack<pair<char,int>> sk;
        priority_queue<pair<char,int>,vector<pair<char,int>>,cmp> que;
        for(auto it : S) ++mp[it];
        for(auto it : mp) que.push(make_pair(it.first,it.second));
        while(!que.empty()){
            //找到与pre不同、个数最多的字母
            while(!que.empty()&&que.top().first==pre){
                sk.push(que.top());
                que.pop();
            }
            if(que.empty()) return "";
            pre = que.top().first;
            int t = que.top().second-1;
            que.pop();
            if(t!=0) que.push(make_pair(pre,t));
            while(!sk.empty()){
                que.push(sk.top());
                sk.pop();
            }
            ans += pre;
        }
        return ans;
    }
};

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!