String arrangement
class Solution {
class Pair {
int count;
char character;
Pair(int count, char character) {
this.count = count;
this.character = character;
}
}
public String longestDiverseString(int a, int b, int c) {
PriorityQueue<Pair> pq = new PriorityQueue<Pair>((x, y) ->
(y.count - x.count)
);
if (a > 0) pq.offer(new Pair(a, 'a'));
if (b > 0) pq.offer(new Pair(b, 'b'));
if (c > 0) pq.offer(new Pair(c, 'c'));
StringBuilder sb = new StringBuilder();
while (!pq.isEmpty()) {
Pair curt = pq.poll();
int count = curt.count;
char ch = curt.character;
int n = sb.length();
if (sb.length() >= 2 && sb.charAt(n - 1) == ch && sb.charAt(n - 2) == ch) {
if (pq.isEmpty()) break;
Pair temp = pq.poll();
sb.append(temp.character);
if (--temp.count > 0) {
pq.offer(new Pair(temp.count, temp.character));
}
} else {
count--;
sb.append(ch);
}
if (count > 0) pq.offer(new Pair(count, ch));
}
return sb.toString();
}
}Last updated
Was this helpful?