Description
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, and
- 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"
Constraints:
- 0 <= a, b <= 100
- It is guaranteed such an s exists for the given a and b.
分析
题目的意思是:给定a的数量,b的数量,组成一个字符串,要求连续a或者连续b的数量不超过3.
- 我参考了一下答案,直觉的求解释选择当前所剩最多的待写字母写入字符串中。举一个例子,如果 a= 6, b = 2,那么我们期望写出 ‘aabaabaa’
- 用flag标识变量控制当前需要选择的字母就行了,如果flag为True,则选择’a’,否则选择’b’
- 选择’a’的情况是a的长度大于b,或者res结果里面最后连续两个字符是’b’,否则就需要选择’a’
代码
class Solution:
def strWithout3a3b(self, a: int, b: int) -> str:
res=''
flag=False
while(a>0 or b>0):
if(len(res)>=2 and res[-1]==res[-2]):
if(res[-1]=='b'):
flag=True
else:
flag=False
else:
if(a>b):
flag=True
else:
flag=False
if(flag):
res+='a'
a-=1
else:
res+='b'
b-=1
return res