← All problems

1405. Longest Happy String

MediumOpen on LeetCodeProblem statement

Problem Statement

1405. Longest Happy String

Medium


A string s is called happy if it satisfies the following conditions:

Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "".

A substring is a contiguous sequence of characters within a string.

 

Example 1:

Input: a = 1, b = 1, c = 7
Output: "ccaccbcc"
Explanation: "ccbccacc" would also be a correct answer.

Example 2:

Input: a = 7, b = 1, c = 0
Output: "aabaa"
Explanation: It is the only correct answer in this case.

 

Constraints:

Java

Source file
class Solution {
    private record Node(int freq, char ch) {
    }

    public String longestDiverseString(int a, int b, int c) {
        Queue<Node> pq = new PriorityQueue<>((m, n) -> n.freq - m.freq);
        if(a==0 && b==0 && c==0)
            return "";
        StringBuilder sb = new StringBuilder();
        if (a > 0)
            pq.offer(new Node(a, 'a'));
        if (b > 0)
            pq.offer(new Node(b, 'b'));
        if (c > 0)
            pq.offer(new Node(c, 'c'));
        Node top = pq.poll();
        while (top!=null) {
            int f = top.freq, k = !pq.isEmpty() && pq.peek().freq>f ? 1 : 2;
            char ch = top.ch;
            while (f > 0 && k-- > 0) {
                sb.append(ch);
                f--;
            }
            // System.out.println(pq);
            if(pq.isEmpty())
                break;
            top = pq.poll();
            if (f > 0) 
                pq.offer(new Node(f, ch));
        }
        return sb.toString();
    }
}