GuilinDev

Lc0984

05 August 2008

984 String Without AAA or BBB

给两个整数a和b,造一个字符串里面刚好有a个a和b个b,但不会出现连续三次的aaa或bbb,返回任意一个结果

Greedy

1
2
3
4
5
6
7
8
9
10
11
12
public String strWithout3a3b(int A, int B) {
  StringBuilder res = new StringBuilder(A + B);
  char a = 'a', b = 'b';
  int i = A, j = B;
  if (B > A) { a = 'b'; b = 'a'; i = B; j = A; }
  while (i-- > 0) {
    res.append(a);
    if (i > j) { res.append(a); --i; }
    if (j-- > 0) res.append(b);
  }
  return res.toString();
}
1
2
3
4
5
string strWithout3a3b(int A, int B, char a = 'a', char b = 'b') {
  if (B > A) return strWithout3a3b(B, A, b, a);
  if (B == 0) return string(A, a);
  return string(A > B ? 2 : 1, a) + b + strWithout3a3b(A - (A > B ? 2 : 1), B - 1, a, b);
}