Leetcode中Minimum Add to Make Parentheses Valid用js实现

题目描述:

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 with B), where A and Bare valid strings, or
  • It can be written as (A), where A 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)
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值