Parentheses strings are strings containing only the characters ‘(‘ and ‘)’.
A parentheses string is considered balanced when its opening parentheses align with its closing parentheses.
For example, "()" and "(())" are balanced, while ")(", "())(" are not.
Given a string consisting of the same number of opening and closing parentheses, determine the minimum number of character swaps required to make the string a balanced parentheses string.
Example
s = "))(("
Swap the first and the last characters to get "()()", a balanced parentheses string.
The minimum number of swaps is 1.
题目给了一串只包含 '(' 和 ')' 的字符串,且左右括号数量相等。
你的任务是: 通过交换字符的位置,使括号序列变成合法括号串,并求最小交换次数。
核心点:
- 括号数量相等,但顺序可能乱了,例如
))((。 - 你可以任意交换两个字符(类似 bubble swap 中的字符互换)。
- 目的是让括号变得合法(balanced)——每个
'('都有对应的')'。
解法直觉:
- 从左往右扫描,记录“未匹配右括号”的数量。
- 当遇到多余的
')'时,需要从后面找'('来交换。 - 累积所有需要交换的次数。
示例 ))((:
交换首尾即可变成 "()()",答案为 1。
VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 Tiktok、Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备 Tiktok 或类似工程向公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。