Skip to content

984. String Without AAA or BBB

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  string strWithout3a3b(int A, int B, char a = 'a', char b = 'b') {
    if (A < B)
      return strWithout3a3b(B, A, b, a);
    if (B == 0)
      return string(min(A, 2), a);

    const int useA = min(A, 2);
    const int useB = (A - useA >= B) ? 1 : 0;
    return string(useA, a) + string(useB, b) +
           strWithout3a3b(A - useA, B - useB, a, b);
  }
};
Back to top