767. Reorganize String
[Medium] 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]
.
题目:给定一个字符串S
,检查是否能重新排布其中的字母,使得两相邻的字符不同。若可行,输出任意可行的结果。若不可行,返回空字符串。
思路:按照字符的频率构建优先队列。每次优先考虑添加频率最高的字符,如果冲突,则考虑添加频率次高的字符。
class Solution {
public:
string reorganizeString(string S) {
int arr[26] = {0};
for(auto c : S)
arr[c-'a'] += 1;
priority_queue<pair<int, char>, vector<pair<int, char>>> pq;
for(int i = 0; i < 26; ++i){
if(arr[i] > (S.size()+1)/2)
return "";
if(arr[i] > 0)
pq.push({arr[i], 'a'+i});
}
string res;
while(!pq.empty()){
pair<int, char> p1 = pq.top();
pq.pop();
if(res.empty() || res.back() != p1.second){
res += p1.second;
if(p1.first > 1)
pq.push({p1.first-1, p1.second});
}
else{
// 如果队列当前最高频的字符 与 结果字符串的最后一个字符相同
// 则考虑添加次高频的字符
if(pq.empty())
return "";
pair<int, char> p2 = pq.top();
pq.pop();
res += p2.second;
if(p2.first > 1)
pq.push({p2.first-1, p2.second});
pq.push(p1);
}
}
return res;
}
};