[LeetCode] String Without AAA or BBB

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public:
string strWithout3a3b(int a, int b) {
if(b == 0) return string(a,'a');
if(a ==0) return string(b, 'b');
string res(a + b, '#');
int i = 0;
while(a != b and a and b) {
if(a > b) {
res[i] = res[i + 1] = 'a';
res[i + 2] = 'b';
a -= 2;
b -= 1;
} else {
res[i] = res[i + 1] = 'b';
res[i + 2] = 'a';
a -= 1;
b -= 2;
}
i += 3;
}

while(a and b) {
if(a and b) {
res[i] = 'a';
res[i+1] = 'b';
i += 2;
a -=1, b -= 1;
} else if(a) {
res[i] = 'a';
a-=1;
i += 1;
} else {
res[i] = 'b';
b -= 1;
i += 1;
}
}

if(a == 2) res[i] = res[i + 1] = 'a';
else if(a == 1) res[i] = 'a';
else if(b == 2) res[i] = res[i + 1] = 'b';
else if(b == 1) res[i] = 'b';

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/29/PS/LeetCode/string-without-aaa-or-bbb/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.