LeetCode 题解工作台
构造最长的新字符串
给你三个整数 x , y 和 z 。 这三个整数表示你有 x 个 "AA" 字符串, y 个 "BB" 字符串,和 z 个 "AB" 字符串。你需要选择这些字符串中的部分字符串(可以全部选择也可以一个都不选择),将它们按顺序连接得到一个新的字符串。新字符串不能包含子字符串 "AAA" 或者 "BBB…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们观察发现,字符串 `'AA'` 之后只能跟 `'BB'`,而字符串 `'AB'` 可以放在字符串开头或结尾。因此: - 如果 $x \lt y$,那么我们可以先交替放置 `'BBAABBAA..BB'`,一共放置 个 `'AA'` 和 个 `'BB'`,然后放置剩余的 个 `'AB'`,总长度为 $(x \times 2 + z + 1) \times 2$;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你三个整数 x ,y 和 z 。
这三个整数表示你有 x 个 "AA" 字符串,y 个 "BB" 字符串,和 z 个 "AB" 字符串。你需要选择这些字符串中的部分字符串(可以全部选择也可以一个都不选择),将它们按顺序连接得到一个新的字符串。新字符串不能包含子字符串 "AAA" 或者 "BBB" 。
请你返回 新字符串的最大可能长度。
子字符串 是一个字符串中一段连续 非空 的字符序列。
示例 1:
输入:x = 2, y = 5, z = 1 输出:12 解释: 我们可以按顺序连接 "BB" ,"AA" ,"BB" ,"AA" ,"BB" 和 "AB" ,得到新字符串 "BBAABBAABBAB" 。 字符串长度为 12 ,无法得到一个更长的符合题目要求的字符串。
示例 2:
输入:x = 3, y = 2, z = 2 输出:14 解释:我们可以按顺序连接 "AB" ,"AB" ,"AA" ,"BB" ,"AA" ,"BB" 和 "AA" ,得到新字符串 "ABABAABBAABBAA" 。 字符串长度为 14 ,无法得到一个更长的符合题目要求的字符串。
提示:
1 <= x, y, z <= 50
解题思路
方法一:分类讨论
我们观察发现,字符串 'AA' 之后只能跟 'BB',而字符串 'AB' 可以放在字符串开头或结尾。因此:
- 如果 ,那么我们可以先交替放置
'BBAABBAA..BB',一共放置 个'AA'和 个'BB',然后放置剩余的 个'AB',总长度为 ; - 如果 ,那么我们可以先交替放置
'AABBAABB..AA',一共放置 个'BB'和 个'AA',然后放置剩余的 个'AB',总长度为 ; - 如果 ,我们只需要交替放置
'AABB',一共放置 个'AA'和 个'BB',然后放置剩余的 个'AB',总长度为 。
时间复杂度 ,空间复杂度 。
class Solution:
def longestString(self, x: int, y: int, z: int) -> int:
if x < y:
return (x * 2 + z + 1) * 2
if x > y:
return (y * 2 + z + 1) * 2
return (x + y + z) * 2
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(x _y_ z) in the worst case due to three nested counts and possible transitions. Space complexity also depends on DP state storage and recursion stack, typically O(x _y_ z). Optimizations with memoization reduce repeated computations. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect discussion of state representation and last-two-character tracking.
- question_mark
Check understanding of how AB strings can always be safely inserted.
- question_mark
Probe whether the candidate identifies DP transitions versus greedy simplifications.
常见陷阱
外企场景- error
Forgetting to prevent AAA or BBB when placing AA or BB consecutively.
- error
Overcomplicating AB handling instead of using all of them greedily.
- error
Incorrect DP state indexing leading to repeated calculations or missed cases.
进阶变体
外企场景- arrow_right_alt
Limit the number of AB strings that can be used and adjust DP transitions accordingly.
- arrow_right_alt
Introduce a third forbidden substring pattern like AAB or BBA for stricter constraints.
- arrow_right_alt
Allow any string length for AA, BB, and AB, requiring more general state tracking.