题目描述:
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:
Swill consist of lowercase letters and have length in range[1, 500].
class Solution {
public:
string reorganizeString(string S) {
string result="";
unordered_map<char,int> count;
priority_queue<pair<int,char>> q;
for(char c:S) count[c]++;
for(auto x:count) {
// 最大频率的字符最多为其他字符总数加一
if(x.second*2-1>S.size()) return "";
q.push({x.second,x.first}); // 将字符和频率加入优先队列
}
// 取频率最大的两个字符
while(q.size()>=2) {
pair p1=q.top();
q.pop();
pair p2=q.top();
q.pop();
result.push_back(p1.second);
result.push_back(p2.second);
p1.first--, p2.first--;
if(p1.first>0) q.push(p1);
if(p2.first>0) q.push(p2);
}
if (q.size()>0) result.push_back(q.top().second);
return result;
}
};
390



被折叠的 条评论
为什么被折叠?



