贪心算法
Given two integers
A
andB
, return any stringS
such that:
S
has lengthA + B
and contains exactlyA
'a'
letters, and exactlyB
'b'
letters;- The substring
'aaa'
does not occur inS
;- The substring
'bbb'
does not occur inS
.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"Note:
0 <= A <= 100
0 <= B <= 100
- It is guaranteed such an
S
exists for the givenA
andB
.
private static String strWithout3a3b2(int A, int B) {
if (A > (B+1)<<1 || B > (A+1)<<1) return "noway!";
String sb = new String();
do {
if (A >= B) { //a多,尽量先消费a(贪心策略)
if (sb.endsWith("aa")) { //实在不能消耗a才消费b
sb = sb.concat("b");
B--;
} else { //先消费a
sb = sb.concat("a");
A--;
}
} else {
if (sb.endsWith("bb")) {
sb = sb.concat("a");
A--;
} else {
sb = sb.concat("b");
B--;
}
}
} while (A>0 || B>0); //只要A或B不等于0,则一直循环
return sb;
}