Q:
给定两个整数 A 和 B,返回任意字符串 S,要求满足:
-
S的长度为A + B,且正好包含A个'a'字母与B个'b'字母; - 子串
'aaa'没有出现在S中; - 子串
'bbb'没有出现在S中。
示例 1:
输入:A = 1, B = 2 输出:"abb" 解释:"abb", "bab" 和 "bba" 都是正确答案。
示例 2:
输入:A = 4, B = 1 输出:"aabaa"
链接:https://leetcode-cn.com/problems/string-without-aaa-or-bbb/description/
思路:贪心算法
代码:
class Solution:
def strWithout3a3b(self, A, B):
"""
:type A: int
:type B: int
:rtype: str
"""
a = 'a'
b = 'b'
if A < B:
A, B = B, A
a, b = b, a
C = min(A-B, B)
if C == 0:
return (a+b)*B
ans = (2*a+b)*C
if C == B:
D = A-2*B
ans += D*a
return ans
else:
ans += (a+b)*(2*B-A)
return ans