LeetCode Weekly Contest 121

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

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
复制代码

 

posted @   Asimple  阅读(193)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示