LeetCode 984. String Without AAA or BBB
考点 | 难度 |
---|---|
Greedy | Easy |
题目
Given two integers a and b, return any string s such that:
s has length a + b and contains exactly a ‘a’ letters, and exactly b ‘b’ letters,
The substring ‘aaa’ does not occur in s, and
The substring ‘bbb’ does not occur in s.
思路
如果已经有aa,下一个必须是b,如果已经有bb,下一个必须是a。其他情况下如果a的个数大于b,下一个是a。
答案
class Solution(object):
def strWithout3a3b(self, a, b):
ans = []
while a + b > 0:
if ans[-2 :] == ['a', 'a']:
b -= 1
ans.append('b')
elif ans[-2 :] == ['b', 'b']:
a -= 1
ans.append('a')
elif a >= b:
a -= 1
ans.append('a')
else:
b -= 1
ans.append('b')
return ''.join(ans)