• 【leetcode】984. String Without AAA or BBB


    题目如下:

    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 Aand B.

    解题思路:由于aaa/bbb是不允许的,因此Output必定只能由a,aa,b,bb四种组合。假设这四种组合的出现次数分别是i,j,k,l。那么应该满足 i+2*j = A,k+2*l = B,abs((i+j) - (k+l)) <= 1 (两者的差必须小于等于1,否则可能会出现aaa/bbb的情况)。 接下来只要穷举,找出其中一个符合条件的组合即可。

    代码如下:

    class Solution(object):
        def strWithout3a3b(self, A, B):
            """
            :type A: int
            :type B: int
            :rtype: str
            """
            a_1 = A
            a_2 = A/2
            b_1 = B
            b_2 = B/2
            def calc(a_1,a_2,b_1,b_2):
                for i in range(a_1+1):
                    for j in range(a_2+1):
                        if i + 2*j != A:
                            continue
                        for k in range(b_1+1):
                            for l in range(b_2+1):
                                if k + 2*l != B:
                                    continue
                                if abs(i+j-k-l) <= 1:
                                    return i,j,k,l
            i,j,k,l = calc(a_1,a_2,b_1,b_2)
            res = ''
            next = 'a' if (i+j) >= (k+l) else 'b'
            while i + j + k + l > 0:
                if next == 'a':
                    if i > 0:
                        res += next
                        i -= 1
                    else:
                        res += next*2
                        j -= 1
                    next = 'b'
                else:
                    if k > 0:
                        res += next
                        k -= 1
                    else:
                        res += next*2
                        l -= 1
                    next = 'a'
            return res
  • 相关阅读:
    ccr1
    与非CCR代码互操作
    ccr test
    CCR
    tpl + ccr
    TPL
    利用 Rational ClearCase ClearMake 构建高性能的企业级构建环境
    Android错误:Re-installation failed due to different application signatures
    C 单例模式
    C 工厂模式 还有其他的模式
  • 原文地址:https://www.cnblogs.com/seyjs/p/10330465.html
Copyright © 2020-2023  润新知