题目描述:
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.
有道翻译是:
给定一个包含'('和')'括号的字符串,我们添加最小数量的括号('('或')',并在任何位置),以便得到的括号字符串是有效的。
在形式上,当且仅当:
它是空字符串,或者
它可以写成AB (A与B连接),其中A和B是有效的字符串,或者
它可以写成(A),其中A是一个有效的字符串。
给定一个圆括号字符串,返回我们必须添加的最小圆括号数量,以使结果字符串有效
这个题是括号匹配的进化版,个人理解就是如果所给的字符串括号匹配成功则返回0,否则有几个括号不能匹配就返回几
代码如下:
/**
* @param {string} S
* @return {number}
*/
var minAddToMakeValid = function(S) {
var stack = [];
var n = 0;
for(var i=0;i<S.length;i++){
if(S.charAt(i) === '('){
stack.push(")")
}else if(S.charAt(i) === ')'){
if(stack[stack.length-1] == ')'){
stack.pop()
}else{
++n
}
}
}
return n+parseInt(stack.length)
};