Given two integers A
and B
, return any string S
such that:
S
has lengthA + B
and contains exactlyA
'a'
letters, and exactlyB
'b'
letters;- The substring
'aaa'
does not occur inS
; - The substring
'bbb'
does not occur inS
.
Example 1:
Input: A = 1, B = 2 Output: "abb" Explanation: "abb", "bab" and "bba" are all correct answers.
Example 2:
Input: A = 4, B = 1 Output: "aabaa"
Note:
0 <= A <= 100
0 <= B <= 100
- It is guaranteed such an
S
exists for the givenA
andB
.
思路:先aabbaabb这样放,当放a(或者b)的时候发现b(或者a)不够(比如出现5个a,一个b的情况,最好也是aabaaa,无法满足),就只放一个a(或者b)
class Solution:
def strWithout3a3b(self, A, B):
"""
:type A: int
:type B: int
:rtype: str
"""
s = A+B
res = []
cs = ['a', 'b']
cnt = [A, B]
idx = 0 if A>B else 1
while len(res)<s:
res.append(cs[idx])
cnt[idx]-=1
if (cnt[1-idx]-1)//2<cnt[idx]:
res.append(cs[idx])
cnt[idx]-=1
idx=1-idx
return ''.join(res[:(A+B)])
s=Solution()
print(s.strWithout3a3b(0, 0))
print(s.strWithout3a3b(1, 2))
print(s.strWithout3a3b(4, 1))