Given two integers A
and B
, return any string S
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
.
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Solution { public: string strWithout3a3b(int A, int B) { char a = 'a'; char b = 'b'; if (B > A) { swap(A, B); swap(a, b); } string ans; while (A || B) { if (A > 0) { ans += a; --A; } if (A > B) { ans += a; --A; } if (B > 0) { ans += b; --B; } } return ans; } }; |
C++ / overload
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Solution { public: string strWithout3a3b(int A, int B, char a = 'a', char b = 'b') { if (B > A) return strWithout3a3b(B, A, b, a); string ans; while (A || B) { if (A > 0) { ans += a; --A; } if (A > B) { ans += a; --A; } if (B > 0) { ans += b; --B; } } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment