给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。
若可行,输出任意可行的结果。若不可行,返回空字符串。
示例 1:
输入: S = "aab"
输出: "aba"
示例 2:
输入: S = "aaab"
输出: ""
注意:
S 只包含小写字母并且长度在[1, 500]区间内。
解法:优先队列--大顶堆
1 class Solution {
2 public:
3 //vector<int> ret;
4 // struct static cmp{
5 // bool operator()(char ch1, char ch2){
6 // return ret[ch1 - 'a'] < ret[ch2 - 'a'];
7 // }
8 // };
9 string reorganizeString(string S) {
10 int len = S.size();
11 if(len < 2)
12 return S;
13 vector<int> ret(26, 0);
14 int maxlen = 0;
15 for(char item : S){
16 ret[item - 'a']++;
17 maxlen = max(maxlen, ret[item - 'a']);
18 }
19 if(maxlen > (len + 1) / 2)
20 return "";
21
22 auto cmp = [&](const char& letter1, const char& letter2) {
23 return ret[letter1 - 'a'] < ret[letter2 - 'a'];
24 };
25
26 priority_queue<char, vector<char>, decltype(cmp)> q(cmp);
27 for(char ch = 'a'; ch<='z'; ch++){
28 if(ret[ch - 'a'])
29 q.push(ch);
30 }
31 string ans = "";
32 while(q.size() > 1){
33 char letter1 = q.top();
34 q.pop();
35 char letter2 = q.top();
36 q.pop();
37 ans = ans + letter1 + letter2;
38 int index1 = letter1 - 'a', index2 = letter2 - 'a';
39 ret[index1]--;
40 ret[index2]--;
41 if(ret[letter1 - 'a'])
42 q.push(letter1);
43 if(ret[letter2 - 'a'])
44 q.push(letter2);
45 }
46 if(q.size() > 0)
47 ans += q.top();
48 return ans;
49 }
50 };
1 class Solution {
2 public:
3 string reorganizeString(string S) {
4 int len = S.size();
5 if(len < 2)
6 return S;
7 vector<int> ret(26, 0);
8 for(char item : S)
9 ret[item - 'a']++;
10 priority_queue<pair<int, char>, vector<pair<int, char> >, less<pair<int, char> > > q;
11 for(char ch = 'a'; ch <= 'z'; ch++){
12 if(ret[ch - 'a']){
13 if(ret[ch - 'a'] > (len + 1) / 2)
14 return "";
15 q.push(make_pair(ret[ch - 'a'], ch));
16 }
17 }
18 string ans = "";
19 pair<int, char> pre(0, ' ');
20 while(q.size()){
21 pair<int,char> cur = q.top();
22 q.pop();
23 ans += cur.second;
24 cur.first--;
25 if(pre.first)
26 q.push(pre);
27 pre = cur;
28 }
29 return ans;
30 }
31 };