- 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
Example 1:
Input: S = “aab”
Output: “aba”
Example 2:
Input: S = “aaab”
Output: “”
Notice
S will consist of lowercase letters and have length in range [1, 500].
解法1:基于maxHeap
注意:
- 当某字符的个数>整个字符串的一半时,返回""。
- int thresh = (n & 0x1) ? n / 2 + 1 : n / 2; 可以简化为 int thresh = (n + 1) / 2;
- 一个比较好用的input是"aaaabbbcccdefg"。
代码如下:
class Solution {
public:
/**
* @param S: a string
* @return: return a string
*/
string reorganizeString(string &S) {
int n = S.size();
string result;
if (n == 0) return result;
// int thresh = (n & 0x1) ? n / 2 + 1 : n / 2;
unordered_map<char, int> um;
priority_queue<pair<int, char>> pq;
for (int i = 0; i < n; ++i) {
um[S[i]]++;
if (um[S[i]] > (n + 1) / 2) return "";
}
for (auto n : um) pq.push({n.second, n.first});
while(pq.size() >= 2) {
pair<int, char> topA = pq.top(); pq.pop();
pair<int, char> topB = pq.top(); pq.pop();
result.push_back(topA.second);
if (topA.first > 1) pq.push({topA.first - 1, topA.second});
result.push_back(topB.second);
if (topB.first > 1) pq.push({topB.first - 1, topB.second});
}
if (pq.size() > 0) {
pair<int, char> top = pq.top(); pq.pop();
result.push_back(top.second);
}
return result;
}
};
注意:该题可以扩展到相邻字符至少间隔为k的情形,即[LeetCode] Rearrange String k Distance Apart 按距离为k隔离重排字符串。该题为k=2的特殊情形。
代码如下://参考自https://www.cnblogs.com/grandyang/p/5586009.html
class Solution {
public:
string rearrangeString(string str, int k) {
if (k == 0) return str;
string res;
int len = (int)str.size();
unordered_map<char, int> m;
priority_queue<pair<int, char>> q;
for (auto a : str) ++m[a];
for (auto it = m.begin(); it != m.end(); ++it) {
q.push({it->second, it->first});
}
while (!q.empty()) {
vector<pair<int, int>> v;
int cnt = min(k, len);
for (int i = 0; i < cnt; ++i) {
if (q.empty()) return "";
auto t = q.top(); q.pop();
res.push_back(t.second);
if (--t.first > 0) v.push_back(t);
--len;
}
for (auto a : v) q.push(a);
}
return res;
}
};
代码同步在:
https://github.com/luqian2017/Algorithm