-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL767.java
More file actions
80 lines (76 loc) · 2.96 KB
/
L767.java
File metadata and controls
80 lines (76 loc) · 2.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.util.PriorityQueue;
import java.util.Queue;
class Solution767 {
class Solution {
// We use this structure to store counts of occurences of each character
class CharCount implements Comparable<CharCount> {
char ch;
int count;
public CharCount(char ch, int count) {
this.ch = ch;
this.count = count;
}
@Override
public int compareTo(CharCount o) {
return Integer.compare(o.count, this.count);
}
}
/**
* 767. Reorganize String https://leetcode.com/problems/reorganize-string/description/
*
* @param S Input string
* @return A permutation of S where none of the same chars are adjacent
* @timeComplexity O(n) where n is the length of string
* @spaceComplexity O(1) Constant amount of space in the priority queue (26 chars only)
*/
public String reorganizeString(String S) {
int[] counts = new int[26];
for (char c : S.toCharArray()) {
counts[c - 'a']++;
}
int maxRepeated = 0;
for (int i = 0; i < 26; i++) {
if (counts[i] > 1) {
maxRepeated = Math.max(maxRepeated, counts[i]);
}
}
int threshold = (S.length() % 2 == 0 ? S.length() / 2 : S.length() / 2 + 1);
// If the number of maxrepeated character is majority (> 50%), then we don't have a solution
if (maxRepeated > threshold) {
return "";
} else {
// Put the chars and their counts in priority queue
Queue<CharCount> pq = new PriorityQueue<>();
for (int i = 0; i < 26; i++) {
if (counts[i] > 0) {
pq.add(new CharCount((char) (i + 'a'), counts[i]));
}
}
StringBuffer sb = new StringBuffer();
char prev = 'A';
while (!pq.isEmpty()) {
// Extract max occuring character from queue
CharCount cur = pq.remove();
CharCount temp = null;
if (cur.ch == prev) {
// We already used it, so take out another one to use
temp = cur;
cur = pq.remove();
}
sb.append(cur.ch);
prev = cur.ch;
// Add it back only if we have more of it
if (cur.count > 1) {
cur.count--;
pq.add(cur);
}
// Put the old one back into queue if we took it out
if (temp != null) {
pq.add(temp);
}
}
return sb.toString();
}
}
}
}