力扣921. 使括号有效的最少添加

Problem: 921. 使括号有效的最少添加

题目描述

在这里插入图片描述在这里插入图片描述

思路及解法

1.定义int变量res、need分别记录需要插入的左括号数和所需与左括号配对的右括号数

2.遍历字符串:

2.1.若当为左括号,则need++,表示需要一个右括号与当前左括号配对
2.2.若当前为右括号,则need–,表示已经有一个右括号与左括号配对

2.2.1.若发现当前need == -1则表示需要插入一个左括号即res++

3.返回最后需要插入的左括号数和需要和当前左括号配对的右括号数即res + need

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为给定字符串的长度

空间复杂度:

O ( 1 ) O(1) O(1)

Code

class Solution {
    /**
     * Minimum Add to Make Parentheses Valid
     *
     * @param s Given string
     * @return int
     */
    public int minAddToMakeValid(String s) {
        // Record the number of left bracket insertion requirements
        int res = 0;
        int need = 0;
        for (int i = 0; i < s.length(); ++i) {
            if (s.charAt(i) == '(') {
                // Add one to the required number of right parentheses
                need++;
            }
            if (s.charAt(i) == ')') {
                // Add one to the required number of left parentheses
                need--;
                if (need == -1) {
                    need = 0;
                    //Subtract one to the required number of right parentheses
                    res++;
                }
            }
        }
        return need + res;
    }
}
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值