标签:open substr xpl 没有 坑点 question rect a+b code
上周因为感冒没有刷题,两个星期没有刷题,没手感了,思维也没有那么活跃了,只刷了一道,下个星期努力。
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;‘aaa‘
does not occur in S
;‘bbb‘
does not occur in S
.
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
S
exists for the given A
and B
.题目意思:给出A代表a的个数,B代表b的个数,让你制造一个长度为A+B的字符串S,且满足"aaa"和"bbb"不是S的子串。
题目很简单,就是坑点多。我把所有的坑都踩了。下面是代码:
class Solution { public: string strWithout3a3b(int A, int B) { string ans = ""; if( B > A ) { while( B && A ) { if( B - A >= 2 && A ) { ans += "bba"; B -= 2; A -- ; } else if( B-A && A ) { ans += "b"; ans += "a"; B --; A --; } } if( B ) while( B -- ) ans += "b"; if( A ) ans += "a"; } else if( A > B ){ while( B && A ) { if( A - B >= 2 && B ) { ans += "aab"; A -= 2; B -- ; } else if( A-B && B ) { ans += "a"; ans += "b"; B --; A --; } } if( A ) while( A -- ) ans += "a"; if( B ) ans += "b"; } else { while( B ) { ans += "ab"; B --; } } return ans; } };
标签:open substr xpl 没有 坑点 question rect a+b code
原文地址:https://www.cnblogs.com/Asimple/p/10325986.html