0767. Reorganize String

# 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].

## 解题思路 #

``````    string reorganizeString(string S) {
vector<int> mp(26);
int n = S.size();
for (char c: S)
++mp[c-'a'];
priority_queue<pair<int, char>> pq;
for (int i = 0; i < 26; ++i) {
if (mp[i] > (n+1)/2) return "";
if (mp[i]) pq.push({mp[i], i+'a'});
}
queue<pair<int, char>> myq;
string ans;
while (!pq.empty() || myq.size() > 1) {
if (myq.size() > 1) { // 注意这里要大于 1，如果是等于 1 的话，频次大的元素一直在输出了，答案就不对了。
auto cur = myq.front();
myq.pop();
if (cur.first != 0) pq.push(cur);
}
if (!pq.empty()) {
auto cur = pq.top();
pq.pop();
ans += cur.second;
cur.first--;
myq.push(cur);
}
}
return ans;
}
``````

## 代码 #

``````
package leetcode

import (
"sort"
)

func reorganizeString(S string) string {
fs := frequencySort767(S)
if fs == "" {
return ""
}
bs := []byte(fs)
ans := ""
j := (len(bs)-1)/2 + 1
for i := 0; i <= (len(bs)-1)/2; i++ {
ans += string(bs[i])
if j < len(bs) {
ans += string(bs[j])
}
j++
}
return ans
}

func frequencySort767(s string) string {
if s == "" {
return ""
}
sMap := map[byte]int{}
cMap := map[int][]byte{}
sb := []byte(s)
for _, b := range sb {
sMap[b]++
if sMap[b] > (len(sb)+1)/2 {
return ""
}
}
for key, value := range sMap {
cMap[value] = append(cMap[value], key)
}

var keys []int
for k := range cMap {
keys = append(keys, k)
}
sort.Sort(sort.Reverse(sort.IntSlice(keys)))
res := make([]byte, 0)
for _, k := range keys {
for i := 0; i < len(cMap[k]); i++ {
for j := 0; j < k; j++ {
res = append(res, cMap[k][i])
}
}
}
return string(res)
}

``````

Sep 6, 2020