# 767 Reorganize String

## 767. [Reorganize String](https://leetcode.com/problems/reorganize-string/description/)

## 1. Question

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

## 2. Implementation

**(1) Greedy**

```java
class Solution {
    public String reorganizeString(String S) {
        if (S == null || S.length() <= 1) {
            return S;
        }

        int[] count = new int[256];

        for (char c : S.toCharArray()) {
            count[c]++;
        }

        PriorityQueue<CharInfo> maxHeap = new PriorityQueue<>();

        for (int i = 0; i < 256; i++) {
            if (count[i] > (S.length() + 1) / 2) {
                return "";
            }

            if (count[i] != 0) {
                maxHeap.add(new CharInfo((char)i, count[i]));
            }
        }

        StringBuilder res = new StringBuilder();

        while (!maxHeap.isEmpty()) {
            CharInfo c1 = maxHeap.remove();

            if (res.length() == 0 || c1.val != res.charAt(res.length() - 1)) {
                res.append(c1.val);

                if (--c1.count > 0) {
                    maxHeap.add(c1);
                }
            }
            else {
                CharInfo c2 = maxHeap.remove();

                res.append(c2.val);

                if (--c2.count > 0) {
                    maxHeap.add(c2);
                }
                maxHeap.add(c1);
            }
        }
        return res.toString();
    }

    class CharInfo implements Comparable<CharInfo> {
        char val;
        int count;

        public CharInfo(char val, int count) {
            this.val = val;
            this.count = count;
        }

        public int compareTo(CharInfo that) {
            return that.count - this.count;
        }
    }
}
```

## 3. Time & Space Complexity

Greedy: 时间复杂度O(nlogn), n是S的长度, 空间复杂度O(n)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/algorithm-practice/leetcode/heap/767-reorganize-string.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
