# 984. String Without AAA or BBB

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`.

``````class Solution {
public:
string strWithout3a3b(int a, int b) {
if (a == 0) return string(b, 'b');
if (b == 0) return string(a, 'a');
if (a == b) return "ab" + strWithout3a3b(a - 1, b - 1);
if (a > b) return "aab" + strWithout3a3b(a - 2, b - 1);
return "bba" + strWithout3a3b(a - 1, b - 2);
}
};
``````

``````class Solution {
public:
string strWithout3a3b(int a, int b) {
string res;
while (a && b) {
if (a > b) {
res += "aab";
--a;
} else if (b > a) {
res += "bba";
--b;
} else {
res += "ab";
}
--a; --b;
}
res += string(a, 'a');
res += string(b, 'b');
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/984

https://leetcode.com/problems/string-without-aaa-or-bbb/

https://leetcode.com/problems/string-without-aaa-or-bbb/discuss/226740/Clean-C%2B%2Bpython-solution

https://leetcode.com/problems/string-without-aaa-or-bbb/discuss/227038/C%2B%2B-short-and-simple-solution

https://leetcode.com/problems/string-without-aaa-or-bbb/discuss/226649/JavaC%2B%2B-(and-Python)-simple-greedy

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation