[
string
greedy
]
Leetcode 0984. String Without AAA or BBB
Problem statement
https://leetcode.com/problems/string-without-aaa-or-bbb/
Solution
If we have more a
than b
, add aab
, if we have more b
than a
, add bba
. If they are equal, add ab
. If we have something in the end, add it to the end.
Complexity
It is O(a + b)
for time and space.
Code
class Solution:
def strWithout3a3b(self, a, b):
ans = []
while a and b:
if a > b:
ans += ["a", "a", "b"]
a, b = a-2, b-1
elif a < b:
ans += ["b", "b", "a"]
a, b = a-1, b-2
else:
ans += ["a", "b"]
a, b = a-1, b-1
return "".join(ans + ["a"] * a + ["b"] * b)