class Solution:
def strWithout3a3b(self, a: int, b: int) -> str:
res = []
while a > 0 or b > 0:
if a > b:
if a >= 2:
res.append('aa')
a -= 2
else:
res.append('a')
a -= 1
if b > 0:
res.append('b')
b -= 1
elif b > a:
if b >= 2:
res.append('bb')
b -= 2
else:
res.append('b')
b -= 1
if a > 0:
res.append('a')
a -= 1
else:
if a > 0:
res.append('a')
a -= 1
if b > 0:
res.append('b')
b -= 1
return ''.join(res)
class Solution {
public:
string strWithout3a3b(int a, int b) {
string res = "";
while (a > 0 || b > 0) {
if (a > b) {
if (a >= 2) {
res += "aa";
a -= 2;
} else {
res += "a";
a -= 1;
}
if (b > 0) {
res += "b";
b -= 1;
}
} else if (b > a) {
if (b >= 2) {
res += "bb";
b -= 2;
} else {
res += "b";
b -= 1;
}
if (a > 0) {
res += "a";
a -= 1;
}
} else {
if (a > 0) {
res += "a";
a -= 1;
}
if (b > 0) {
res += "b";
b -= 1;
}
}
}
return res;
}
};
class Solution {
public String strWithout3a3b(int a, int b) {
StringBuilder res = new StringBuilder();
while (a > 0 || b > 0) {
if (a > b) {
if (a >= 2) {
res.append("aa");
a -= 2;
} else {
res.append("a");
a -= 1;
}
if (b > 0) {
res.append("b");
b -= 1;
}
} else if (b > a) {
if (b >= 2) {
res.append("bb");
b -= 2;
} else {
res.append("b");
b -= 1;
}
if (a > 0) {
res.append("a");
a -= 1;
}
} else {
if (a > 0) {
res.append("a");
a -= 1;
}
if (b > 0) {
res.append("b");
b -= 1;
}
}
}
return res.toString();
}
}
var strWithout3a3b = function(a, b) {
let res = [];
while (a > 0 || b > 0) {
if (a > b) {
if (a >= 2) {
res.push('aa');
a -= 2;
} else {
res.push('a');
a -= 1;
}
if (b > 0) {
res.push('b');
b -= 1;
}
} else if (b > a) {
if (b >= 2) {
res.push('bb');
b -= 2;
} else {
res.push('b');
b -= 1;
}
if (a > 0) {
res.push('a');
a -= 1;
}
} else {
if (a > 0) {
res.push('a');
a -= 1;
}
if (b > 0) {
res.push('b');
b -= 1;
}
}
}
return res.join('');
};
a
and b
, representing the number of letters 'a' and 'b' you must use to construct a string. The task is to create any string using exactly a
'a's and b
'b's such that the string does not contain the substring 'aaa'
or 'bbb'
anywhere. In other words, you cannot have three consecutive 'a's or three consecutive 'b's in your result. Any valid solution is accepted, and you do not have to generate all possibilities—just one valid string that satisfies the constraints.
a = 4
and b = 2
as an example.
a
and b
.