原文链接: https://leetcode-cn.com/problems/minimum-add-to-make-parentheses-valid
英文原文
A parentheses string is valid if and only if:
- It is the empty string,
- It can be written as
AB(Aconcatenated withB), whereAandBare valid strings, or - It can be written as
(A), whereAis a valid string.
You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.
- For example, if
s = "()))", you can insert an opening parenthesis to be"(()))"or a closing parenthesis to be"())))".
Return the minimum number of moves required to make s valid.
Example 1:
Input: s = "())" Output: 1
Example 2:
Input: s = "((("
Output: 3
Example 3:
Input: s = "()" Output: 0
Example 4:
Input: s = "()))(("
Output: 4
Constraints:
1 <= s.length <= 1000s[i]is either'('or')'.
中文题目
给定一个由 '(' 和 ')' 括号组成的字符串 S,我们需要添加最少的括号( '(' 或是 ')',可以在任何位置),以使得到的括号字符串有效。
从形式上讲,只有满足下面几点之一,括号字符串才是有效的:
- 它是一个空字符串,或者
- 它可以被写成
AB(A与B连接), 其中A和B都是有效字符串,或者 - 它可以被写作
(A),其中A是有效字符串。
给定一个括号字符串,返回为使结果字符串有效而必须添加的最少括号数。
示例 1:
输入:"())" 输出:1
示例 2:
输入:"((("
输出:3
示例 3:
输入:"()" 输出:0
示例 4:
输入:"()))(("
输出:4
提示:
S.length <= 1000S只包含'('和')'字符。
通过代码
官方题解
方法一: 平衡法
思路和算法
保证左右括号数量的 平衡: 计算 '(' 出现的次数减去 ')' 出现的次数。如果值为 0,那就是平衡的,如果小于 0,就要在前面补上缺少的 '('。
计算 S 每个前缀子数组的 平衡度。如果值是负数(比如说,-1),那就得在前面加上一个 '('。同样的,如果值是正数(比如说,+B),那就得在末尾处加上 B 个 ')' 。
[solution1-Java]class Solution { public int minAddToMakeValid(String S) { int ans = 0, bal = 0; for (int i = 0; i < S.length(); ++i) { bal += S.charAt(i) == '(' ? 1 : -1; // It is guaranteed bal >= -1 if (bal == -1) { ans++; bal++; } } return ans + bal; } }
[solution1-Python]class Solution(object): def minAddToMakeValid(self, S): ans = bal = 0 for symbol in S: bal += 1 if symbol == '(' else -1 # It is guaranteed bal >= -1 if bal == -1: ans += 1 bal += 1 return ans + bal
复杂度分析
时间复杂度: $O(N)$,其中 $N$ 是
S的长度。空间复杂度: $O(1)$。
统计信息
| 通过次数 | 提交次数 | AC比率 |
|---|---|---|
| 22341 | 30110 | 74.2% |
提交历史
| 提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
|---|