LeetCode Weekly Contest 121
上周因为感冒没有刷题,两个星期没有刷题,没手感了,思维也没有那么活跃了,只刷了一道,下个星期努力。
984. String Without AAA or BBB
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
.
题目意思:给出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; } };
低调做人,高调做事。
标签:
LeetCode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~