【leetcode】984. String Without AAA or BBB
题目如下:
Given two integers
A
andB
, return any stringS
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
.
解题思路:由于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