1405. Longest Happy String

T: O(nlogn), n is a+b+c

S: O(n)

class Solution {
    private record Count(int count, char c){};
    public String longestDiverseString(int a, int b, int c) {
        // use most freq first
        Queue<Count> pq = new PriorityQueue<>((x, y) -> y.count - x.count);
        if (a > 0) {
            pq.offer(new Count(a, 'a'));
        }
        if (b > 0) {
            pq.offer(new Count(b, 'b'));
        }
        if (c > 0) {
            pq.offer(new Count(c, 'c'));
        }

        StringBuilder result = new StringBuilder();
        while (!pq.isEmpty()) {
            Count cur = pq.poll();
            int curCount = cur.count;

            int len = result.length();
            if (len >= 2 && result.charAt(len-1) == cur.c && result.charAt(len-2) == cur.c) {
                if (pq.isEmpty()) {
                    break;
                }

                Count next = pq.poll();
                result.append(next.c);
                if (next.count-1 > 0) { 
                    pq.offer(new Count(next.count-1, next.c));
                }
            } else {
                result.append(cur.c);
                curCount--;
            }

            if (curCount > 0) { 
                pq.offer(new Count(curCount, cur.c));
            }
        }

        return result.toString();
    }
}

/**
T: O(nlogn)
 */

Last updated

Was this helpful?