【Leetcode_总结】984. 不含 AAA 或 BBB 的字符串 - python

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    

【Leetcode_总结】984. 不含 AAA 或 BBB 的字符串 - python