767 Reorganize String

1. Question

Given a stringS, 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:
1
Input: S = "aab"
2
3
Output: "aba"
Copied!
Example 2:
1
Input: S = "aaab"
2
3
Output: ""
Copied!
Note:
  • Swill consist of lowercase letters and have length in range[1, 500].

2. Implementation

(1) Greedy
1
class Solution {
2
public String reorganizeString(String S) {
3
if (S == null || S.length() <= 1) {
4
return S;
5
}
6
7
int[] count = new int[256];
8
9
for (char c : S.toCharArray()) {
10
count[c]++;
11
}
12
13
PriorityQueue<CharInfo> maxHeap = new PriorityQueue<>();
14
15
for (int i = 0; i < 256; i++) {
16
if (count[i] > (S.length() + 1) / 2) {
17
return "";
18
}
19
20
if (count[i] != 0) {
21
maxHeap.add(new CharInfo((char)i, count[i]));
22
}
23
}
24
25
StringBuilder res = new StringBuilder();
26
27
while (!maxHeap.isEmpty()) {
28
CharInfo c1 = maxHeap.remove();
29
30
if (res.length() == 0 || c1.val != res.charAt(res.length() - 1)) {
31
res.append(c1.val);
32
33
if (--c1.count > 0) {
34
maxHeap.add(c1);
35
}
36
}
37
else {
38
CharInfo c2 = maxHeap.remove();
39
40
res.append(c2.val);
41
42
if (--c2.count > 0) {
43
maxHeap.add(c2);
44
}
45
maxHeap.add(c1);
46
}
47
}
48
return res.toString();
49
}
50
51
class CharInfo implements Comparable<CharInfo> {
52
char val;
53
int count;
54
55
public CharInfo(char val, int count) {
56
this.val = val;
57
this.count = count;
58
}
59
60
public int compareTo(CharInfo that) {
61
return that.count - this.count;
62
}
63
}
64
}
Copied!

3. Time & Space Complexity

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