描述
Given a string S
of '('
and ')'
parentheses, we add the minimum number of parentheses ( '('
or ')'
, and in any positions ) so that the resulting parentheses string is valid.
Formally, a parentheses string is valid if and only if:
- It is the empty string, or
- It can be written as
AB
(A
concatenated withB
), whereA
andB
are valid strings, or - It can be written as
(A)
, whereA
is a valid string.
Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.
Example 1:
1 | Input: "())" |
Example 2:
1 | Input: "(((" |
Example 3:
1 | Input: "()" |
Example 4:
1 | Input: "()))((" |
分析
利用栈的特性来模拟左右括号的匹配过程,最后剩下的不能匹配的括号就是需要增加的括号的最小值。
解决方案1(Java)
1 | class Solution { |