上周因为感冒没有刷题,两个星期没有刷题,没手感了,思维也没有那么活跃了,只刷了一道,下个星期努力。

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;
  • The substring '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:

  1. 0 <= A <= 100
  2. 0 <= B <= 100
  3. It is guaranteed such an 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;
    }
};
View Code