String Without AAA or BBB

Problem Id: 984 Difficulty: Medium


Intuition

Solution


class Solution:
    def strWithout3a3b(self, A: int, B: int) -> str:
        ans = [None] * (A + B)
        ca = 'a'
        cb = 'b'
        if A > B:
            ca, cb, A, B = cb, ca, B, A
        for i in range(2, len(ans), 3):
            ans[i] = ca
            A -= 1
        for i in range(0, len(ans), 3):
            ans[i] = cb
            B -= 1
        for i in range(1, len(ans), 3):
            if A:
                A -= 1
                ans[i] = ca
            else:
                ans[i] = cb
        return ''.join(ans)