Longest Happy String
A string is called happy if it does not have any of the strings 'aaa', 'bbb' or 'ccc' as a substring.
Given three integers a, b and c, return any string s, which satisfies following conditions:
- s is happy and longest possible.
- s contains at most a occurrences of the letter 'a', at most b occurrences of the letter 'b' and at most c occurrences of the letter 'c'.
- s will only contain 'a', 'b' and 'c' letters.
If there is no such string s return the empty string "".
Example 1:
Input: a = 1, b = 1, c = 7
Output: "ccaccbcc"
Explanation: "ccbccacc" would also be a correct answer.
Example 2:
Input: a = 2, b = 2, c = 1
Output: "aabbc"
Example 3:
Input: a = 7, b = 1, c = 0
Output: "aabaa"
Explanation: It's the only correct answer in this case.
Constraints:
- 0 <= a, b, c <= 100
- a + b + c > 0
Solution:
class Solution {
class Node {
char c;
int remain;
int count;
public Node(char c, int remain, int count) {
this.c = c;
this.remain = remain;
this.count = count;
}
}
public String longestDiverseString(int a, int b, int c) {
Node A = new Node('a', a, 0);
Node B = new Node('b', b, 0);
Node C = new Node('c', c, 0);
StringBuilder res = new StringBuilder();
boolean picked = true;
while (picked) {
PriorityQueue<Node> pq = new PriorityQueue<>((n1, n2) -> { return Integer.compare(n2.remain, n1.remain); });
pq.offer(A);
pq.offer(B);
pq.offer(C);
picked = false;
while (pq.size() > 0) {
Node curr = pq.poll();
if (curr.remain > 0 && curr.count < 2 && !picked) {
res.append(curr.c);
curr.remain --;
curr.count ++;
picked = true;
} else {
curr.count = 0;
}
}
}
return res.toString();
}
}