767. Reorganize String
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].
方法0: priority_queue
思路:
按照词频排序,统计出最高词频mx,每次pop队首元素round robin 放到mx个string中,最后将所有mx个string连接起来。
class Solution {
public:
string reorganizeString(string S) {
vector<int> count(26, 0);
for (char c: S) count[c - 'a']++;
int mx = *max_element(count.begin(), count.end());
if (2 * mx > S.size() + 1) return "";
priority_queue<pair<int, char>> pq;
for (int i = 0; i < 26; i++) pq.push({count[i], i + 'a'});
vector<string> tmp(mx, "");
int n = 0;
while (!pq.empty()){
auto top = pq.top();
pq.pop();
for (int j = 0; j < top.first; j++) {
tmp[(n++) % mx] += top.second;
}
}
string result;
for (string a: tmp) result += a;
return result;
}
};
方法1:
grandyang: https://www.cnblogs.com/grandyang/p/8799483.html
思路:
统计词频和排序的方法基本一致,但是在重构string 的时候,采用了不一样的方式。每一次从pq里pop出两个最高频的字母,将两个交叉累加到之前的结果中。如果在cnt-1后仍然还剩余字母,再将这个字母送回pq。这样就保证了每一次追加的高频字母之间是不发生重叠的。pq最后也可能出现只剩一个字母的情况,这个时候直接累加即可。因为提前判断了majority 不能多余 (size + 1) / 2 的情况,最后不用担心重叠。
class Solution {
public:
string reorganizeString(string S) {
string res = "";
unordered_map<char, int> m;
priority_queue<pair<int, char>> q;
for (char c : S) ++m[c];
for (auto a : m) {
if (a.second > (S.size() + 1) / 2) return "";
q.push({a.second, a.first});
}
while (q.size() >= 2) {
auto t1 = q.top(); q.pop();
auto t2 = q.top(); q.pop();
res.push_back(t1.second);
res.push_back(t2.second);
if (--t1.first > 0) q.push(t1);
if (--t2.first > 0) q.push(t2);
}
if (q.size() > 0) res.push_back(q.top().second);
return res;
}
};