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.
analysis
The meaning of the question is: given the number of a, the number of b, to form a string, the number of consecutive a or consecutive b should not exceed 3.
- I referred to the answer, and intuitively asked for an explanation, choosing the most letters left to write into the string. For example, if a = 6, b = 2, then we expect to write'aabaabaa'
- Use the flag to identify the variable to control the letter that currently needs to be selected. If the flag is True, select'a', otherwise select'b'
- The case of choosing'a' is that the length of a is greater than b, or the last two consecutive characters in the res result are'b', otherwise you need to choose'a'
Code
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