Leetcode 1304 Solution

This article provides solution to leetcode question 1304 (longest-happy-string)

https://leetcode.com/problems/longest-happy-string

Solution

class Solution:
    def longestDiverseString(self, a: int, b: int, c: int) -> str:
        ans = []

        chars = [
            [a, 'a'],
            [b, 'b'],
            [c, 'c'],
        ]

        last_len = 0
        last_ch = 'x'
        last_cnt = 0

        while True:
            chars.sort(reverse=True)

            if chars[0][1] != last_ch and chars[0][0] > 0:
                ans.append(chars[0][1])
                chars[0][0] -= 1

                last_ch = chars[0][1]
                last_cnt = 1
            elif last_cnt < 2 and chars[0][0] > 0:
                ans.append(chars[0][1])
                chars[0][0] -= 1

                last_ch = chars[0][1]
                last_cnt += 1
            elif chars[1][0] > 0:
                ans.append(chars[1][1])
                chars[1][0] -= 1

                last_ch = chars[1][1]
                last_cnt = 1

            if last_len == len(ans):
                break

            last_len = len(ans)

        return "".join(ans)