题目描述
给定一个字符串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;
}
};
来源:CSDN
作者:weixin_35338624
链接:https://blog.csdn.net/weixin_35338624/article/details/103479516