力扣1541. 平衡括号字符串的最少插入次数

Problem: 1541. 平衡括号字符串的最少插入次数

题目描述

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

思路及解法

Problem: 力扣921. 使括号有效的最少添加
类似于上述题目,不过此时一个左括号要和两个右括号配对

1.同理上述题目,遍历字符串时若遇见一个左括号,则need += 2表示需要两个右括号,但是若此时当所需的的右括号数为奇数时,即need%2==1时需要插入一个右括号(res++),同时也就表示右括号的需求数要减去1(need–)
2.遇见一个右括号时同理上述题目,need–,但是当need==-1时表示此时多出一个右括号需要插入一个左括号同时右括号需要数置为1表示还需要一个右括号,即need==1
3.最后返回res + need即可

复杂度

时间复杂度:

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

空间复杂度:

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

Code

class Solution {
    /**
     * Minimum Insertions to Balance a Parentheses String
     *
     * @param s Given string
     * @return int
     */
    public int minInsertions(String s) {
        //Record the number of parentheses that need to be inserted
        int res = 0;
        //Record the number of close parentheses required
        int need = 0;
        for (int i = 0; i < s.length(); ++i) {
            if (s.charAt(i) == '(') {
                // Two right parentheses are required
                need += 2;
                if (need % 2 == 1) {
                    // Insert a right parenthesis
                    res++;
                    need--;
                }
            }
            if (s.charAt(i) == ')') {
                need--;
                if (need == -1) {   // There is an extra right parenthesis
                    // Need to insert a left parenthesis
                    res++;
                    // A right parenthesis number is also required
                    need = 1;
                }
            }
        }
        return res + need;
    }
}
  • 22
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值