[Swift]LeetCode984. 不含 AAA 或 BBB 的字符串 | String Without AAA or BBB
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:为敢(WeiGanTechnologies)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10311344.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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
和 B
,返回任意字符串 S
,要求满足:
S
的长度为A + B
,且正好包含A
个'a'
字母与B
个'b'
字母;- 子串
'aaa'
没有出现在S
中; - 子串
'bbb'
没有出现在S
中。
示例 1:
输入:A = 1, B = 2 输出:"abb" 解释:"abb", "bab" 和 "bba" 都是正确答案。
示例 2:
输入:A = 4, B = 1 输出:"aabaa"
提示:
0 <= A <= 100
0 <= B <= 100
- 对于给定的
A
和B
,保证存在满足要求的S
。
12ms
1 class Solution { 2 func strWithout3a3b(_ A: Int, _ B: Int) -> String { 3 var A = A 4 var B = B 5 var ret:[Character] = [Character](repeating:" ",count:A+B) 6 for i in 0..<ret.count 7 { 8 if i >= 2 && ret[i-1] == ret[i-2] 9 { 10 if ret[i-1] == "a" 11 { 12 ret[i] = "b" 13 B -= 1 14 } 15 else 16 { 17 ret[i] = "a" 18 A -= 1 19 } 20 } 21 else 22 { 23 if A > B 24 { 25 ret[i] = "a" 26 A -= 1 27 } 28 else 29 { 30 ret[i] = "b" 31 B -= 1 32 } 33 } 34 } 35 return String(ret.reversed()) 36 } 37 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了