To avoid three consecutive ‘a’s or ‘b’s, always append the character with the larger remaining count, but never more than two in a row. If two of the same character are already at the end, append the other character.
Use a greedy loop: at each step, check the last two characters. If the last two are not the same, append the character with more left. If the last two are the same, append the other character. Repeat until both counts are zero.
#include<string>usingnamespace std;
classSolution {
public: string strWithout3a3b(int a, int b) {
string res ="";
while (a >0|| b >0) {
if ((a > b && a >0) || (res.size() >=2&& res.back() =='b'&& res[res.size()-2] =='b')) {
if (a >0) { res +='a'; --a; }
else { res +='b'; --b; }
} else {
if (b >0) { res +='b'; --b; }
else { res +='a'; --a; }
}
}
return res;
}
};
funcstrWithout3a3b(aint, bint) string {
res:= []byte{}
fora > 0||b > 0 {
n:= len(res)
if (a > b&&a > 0) || (n>=2&&res[n-1] =='b'&&res[n-2] =='b') {
ifa > 0 {
res = append(res, 'a')
a-- } else {
res = append(res, 'b')
b-- }
} else {
ifb > 0 {
res = append(res, 'b')
b-- } else {
res = append(res, 'a')
a-- }
}
}
return string(res)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
public String strWithout3a3b(int a, int b) {
StringBuilder res =new StringBuilder();
while (a > 0 || b > 0) {
int n = res.length();
if ((a > b && a > 0) || (n >= 2 && res.charAt(n-1) =='b'&& res.charAt(n-2) =='b')) {
if (a > 0) { res.append('a'); a--; }
else { res.append('b'); b--; }
} else {
if (b > 0) { res.append('b'); b--; }
else { res.append('a'); a--; }
}
}
return res.toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funstrWithout3a3b(a: Int, b: Int): String {
val res = StringBuilder()
var a = a; var b = b
while (a > 0|| b > 0) {
val n = res.length
if ((a > b && a > 0) || (n >=2&& res[n-1] =='b'&& res[n-2] =='b')) {
if (a > 0) { res.append('a'); a-- }
else { res.append('b'); b-- }
} else {
if (b > 0) { res.append('b'); b-- }
else { res.append('a'); a-- }
}
}
return res.toString()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
defstrWithout3a3b(a: int, b: int) -> str:
res = []
while a >0or b >0:
n = len(res)
if (a > b and a >0) or (n >=2and res[-1] =='b'and res[-2] =='b'):
if a >0:
res.append('a')
a -=1else:
res.append('b')
b -=1else:
if b >0:
res.append('b')
b -=1else:
res.append('a')
a -=1return''.join(res)
pubfnstr_without_3a3b(mut a: i32, mut b: i32) -> String {
letmut res = Vec::new();
while a >0|| b >0 {
let n = res.len();
if (a > b && a >0) || (n >=2&& res[n-1] ==b'b'&& res[n-2] ==b'b') {
if a >0 {
res.push(b'a'); a -=1;
} else {
res.push(b'b'); b -=1;
}
} else {
if b >0 {
res.push(b'b'); b -=1;
} else {
res.push(b'a'); a -=1;
}
}
}
String::from_utf8(res).unwrap()
}