Algorithm
Problem Name: 984. String Without AAA or BBB
Problem Link: https://leetcode.com/problems/string-without-aaa-or-bbb/
Given two integers a
and b
, return any string s
such that:
s
has lengtha + b
and contains exactlya
'a'
letters, and exactlyb
'b'
letters,- The substring
'aaa'
does not occur ins
, and - 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"
Constraints:
0 <= a, b <= 100
- It is guaranteed such an
s
exists for the givena
andb
.
Code Examples
#1 Code Example with Javascript Programming
Code -
Javascript Programming
const strWithout3a3b = function (a, b) {
let res = ''
while(a > 0 || b > 0) {
if(endsWith(res, 'aa')) {
res += 'b'
b--
} else if(endsWith(res, 'bb')) {
res += 'a'
a--
} else if(a >= b) {
res += 'a'
a--
} else {
res += 'b'
b--
}
}
return res
function endsWith(str, sub) {
let i = str.length - 1, j = sub.length - 1
for(; i >=0 && j >= 0;i--,j--) {
if(str[i] !== sub[j]) return false
}
if(j >= 0) return false
return true
}
}
Copy The Code &
Try With Live Editor
Input
a = 1, b = 2
Output
"abb"
#2 Code Example with Python Programming
Code -
Python Programming
class Solution:
def strWithout3a3b(self, A: int, B: int) -> str:
if not A and not B: return ''
if A >= B:
a = 2 if A >= 2 else 1
b = 2 if A - a - B < 1 and B >= 2 else 1 if B else 0
return a * 'a' + b * 'b' + self.strWithout3a3b(A - a, B - b)
else:
b = 2 if B >= 2 else 1
a = 2 if B - b - A < 1 and A >= 2 else 1 if A else 0
return b * 'b' + a * 'a' + self.strWithout3a3b(A - a, B - b)
Copy The Code &
Try With Live Editor
Input
a = 1, b = 2
Output
"abb"