Tuesday, January 8, 2019
767. Reorganize String
Version #1 Greedy + PQ
Reference -> LC 358
This is the type of problem that I'm not good at
Greedy is trying to append the chars with the most count first
If the highest frequent char can not be append due to adjacent constraint, we should use the second frequent char instead
class Solution {
public String reorganizeString(String S) {
// every time array characters with highest and second highest priority
int[] count = new int[26];
for (int i = 0; i < S.length(); i++) {
int index = S.charAt(i) - 'a';
if (count[index] > (S.length() + 1) / 2) return "";
count[index]++;
}
// int[0] index of char in 26 array, int[1] count
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> b[1] - a[1]);
for (int i = 0; i < 26; i++) {
if (count[i] > 0) {
maxHeap.offer(new int[]{i, count[i]});
}
}
StringBuilder sb = new StringBuilder();
char prev = 0;
while (!maxHeap.isEmpty()) {
int[] first = maxHeap.poll();
char firstChar = (char) (first[0] + 'a');
if (firstChar != prev) {
sb.append(firstChar);
first[1]--;
prev = firstChar;
if (first[1] > 0) {
maxHeap.offer(first);
}
} else {
if (maxHeap.isEmpty()) return "";
int[] second = maxHeap.poll();
char secondChar = (char) (second[0] + 'a');
sb.append(secondChar);
second[1]--;
prev = secondChar;
if (second[1] > 0) {
maxHeap.offer(second);
}
maxHeap.offer(first);
}
}
return sb.toString();
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment