767. 重构字符串
给定一个字符串S
,检查是否能重新排布其中的字母,使得两相邻的字符不同。
若可行,输出任意可行的结果。若不可行,返回空字符串。
示例 1:
输入: S = "aab" 输出: "aba"
示例 2:
输入: S = "aaab" 输出: ""
注意:
S
只包含小写字母并且长度在[1, 500]
区间内。
class Solution { struct cmp{ bool operator()(pair<int,int>& a,pair<int,int>& b){ if(a.second!=b.second)return a.second<b.second; else return a.first<b.first; } }; public: string reorganizeString(string S) { vector<pair<char,int>>cnt(256,make_pair('\0',0)); for(int i=0;i<cnt.size();i++){ cnt[i].first=(char)i; } for(auto c:S){ cnt[c].second++; } priority_queue<pair<int,int>,vector<pair<int,int>>,cmp> q; for(int i=0;i<256;i++){ if(cnt[i].second>(S.size()+1)/2)return ""; if(cnt[i].second)q.push(cnt[i]); } string res; for(int i=0;i<S.size();i++){ pair<int,int> one=q.top();q.pop(); if(res.empty()||res.back()!=one.first){ res+=one.first; one.second--; q.push(one); }else{ if(q.empty())return ""; pair<int,int> two=q.top();q.pop(); if(res.back()!=two.first){ res+=two.first; two.second--; }else{ return ""; } if(two.second)q.push(two); if(one.second)q.push(one); } } return res; } };