984. String Without AAA or BBB

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/86668081

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;
  • The substring 'bbb' does not occur in S.

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:

  1. 0 <= A <= 100
  2. 0 <= B <= 100
  3. It is guaranteed such an S exists for the given A and B.

思路:先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))
            
            
        
            
            

猜你喜欢

转载自blog.csdn.net/zjucor/article/details/86668081
bbb