LeetCode 题解工作台
使字符串平衡的最小交换次数
给你一个字符串 s , 下标从 0 开始 ,且长度为偶数 n 。字符串 恰好 由 n / 2 个开括号 '[' 和 n / 2 个闭括号 ']' 组成。 只有能满足下述所有条件的字符串才能称为 平衡字符串 : 字符串是一个空字符串,或者 字符串可以记作 AB ,其中 A 和 B 都是 平衡字符串 ,…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
我们用一个变量 记录当前未匹配的左括号的数量,遍历字符串 ,对于每个字符 : - 如果 是左括号,那么 加一;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个字符串 s ,下标从 0 开始 ,且长度为偶数 n 。字符串 恰好 由 n / 2 个开括号 '[' 和 n / 2 个闭括号 ']' 组成。
只有能满足下述所有条件的字符串才能称为 平衡字符串 :
- 字符串是一个空字符串,或者
- 字符串可以记作
AB,其中A和B都是 平衡字符串 ,或者 - 字符串可以写成
[C],其中C是一个 平衡字符串 。
你可以交换 任意 两个下标所对应的括号 任意 次数。
返回使 s 变成 平衡字符串 所需要的 最小 交换次数。
示例 1:
输入:s = "][][" 输出:1 解释:交换下标 0 和下标 3 对应的括号,可以使字符串变成平衡字符串。 最终字符串变成 "[[]]" 。
示例 2:
输入:s = "]]][[[" 输出:2 解释:执行下述操作可以使字符串变成平衡字符串: - 交换下标 0 和下标 4 对应的括号,s = "[]][][" 。 - 交换下标 1 和下标 5 对应的括号,s = "[[][]]" 。 最终字符串变成 "[[][]]" 。
示例 3:
输入:s = "[]" 输出:0 解释:这个字符串已经是平衡字符串。
提示:
n == s.length2 <= n <= 106n为偶数s[i]为'['或']'- 开括号
'['的数目为n / 2,闭括号']'的数目也是n / 2
解题思路
方法一:贪心
我们用一个变量 记录当前未匹配的左括号的数量,遍历字符串 ,对于每个字符 :
- 如果 是左括号,那么 加一;
- 如果 是右括号,那么我们需要判断 是否大于零,如果大于零,那么将当前右括号与左侧最近的一个未匹配的左括号匹配,即 减一。
遍历结束后,得到的一定是形如 "]]]...[[[..."的字符串,我们再贪心地每次将两端的括号交换,这样一次可以消去 个不匹配的左括号。因此,一共需要交换的次数为 。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
class Solution:
def minSwaps(self, s: str) -> int:
x = 0
for c in s:
if c == "[":
x += 1
elif x:
x -= 1
return (x + 1) >> 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each character is processed once during scanning. Space complexity is O(1) since only counters and a few variables are used, no extra arrays or stacks are required. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Do you track the imbalance during iteration or attempt all swap combinations?
- question_mark
Can you optimize space by avoiding explicit swaps and using counters?
- question_mark
How do you determine the exact moment a swap is necessary in a single pass?
常见陷阱
外企场景- error
Forgetting to reset the imbalance counter after each necessary swap, leading to incorrect totals.
- error
Assuming swaps can be minimized by pairing only adjacent brackets rather than using imbalance tracking.
- error
Using extra stacks or arrays unnecessarily, increasing space complexity beyond O(1).
进阶变体
外企场景- arrow_right_alt
Compute minimum swaps to balance strings with multiple types of brackets using a generalized two-pointer invariant.
- arrow_right_alt
Count the number of swaps required if only adjacent bracket swaps are allowed, requiring more careful tracking.
- arrow_right_alt
Determine maximum balanced prefix length after performing at most k swaps, applying similar imbalance tracking.