题目描述
给定两个整数A和B,A代表‘a’的个数,B代表‘b’的个数,字符串的长度为A+B,输出一个字符串,字符串中不能出现‘aaa’或者‘bbb’
例1:
Input: A = 1, B = 2
Output: "abb"
Explanation: "abb", "bab" and "bba" are all correct answers.
例2:
Example 2:
Input: A = 4, B = 1
Output: "aabaa"
思路
字符串a和b组合情况其实与A,B大小有关。如果A>=B,字符串末尾添加‘a’然后A-1。如果A<B或者字符串末尾最后两个字符连续出现相同的两个‘a’,字符串末尾添加‘b’,然后B-1
代码实现
class Solution(object):
def strWithout3a3b(self, A, B):
ans = []
while A or B:
if len(ans) >= 2 and ans[-1] == ans[-2]:
writeA = ans[-1] == 'b'
else:
writeA = A >= B
if writeA:
A -= 1
ans.append('a')
else:
B -= 1
ans.append('b')
return "".join(ans)
网友评论