【leetcode】921. Minimum Add to Make Parentheses Valid

本文介绍了解决LeetCode 921题目的算法思路,通过使用栈数据结构来找出并计算字符串中无法正常匹配的括号数量。详细解释了如何遍历字符数组,以及如何在遇到左括号和右括号时进行入栈和出栈操作,最终返回未匹配括号的总数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【leetcode】921. Minimum Add to Make Parentheses Valid

英文题目:

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 B are 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.

中文释义:题目给你一个字符串,根据括号匹配的规则找出不能正常匹配的括号的个数,例如,“()()”这个就是正常匹配,但是“())”这个就不能正常匹配,最右边的右括号缺少一个左括号来匹配。

Example 1:

Input: “())”
Output: 1

Example2:

Input: “(((”
Output: 3

Example3:

Input: “()”
Output: 0

Example 4:

Input: “()))((”
Output: 4

解题思路

括号匹配一般用的都是栈这种数据结构,这题也是用栈来解决,首先我们可以分两部分来解决这个问题,先将字符串转为字符数组,然后遍历字符数组。1、若栈为空,该字符直接入栈。2、若栈不为空,且字符为“(”,直接入栈,再判断栈顶是否有“)”,这些前面“)”都是不能匹配的右括号,用while循环出栈,直到栈顶不为“)”,出栈一个未匹配的数量就加1。3、遇到字符为“)”,就先判断栈顶是否为“(”,若是,则出栈,若不是,则“)”入栈。4、遍历完字符数组后,再计算栈的长度,此时栈内剩下的元素都是没有匹配的括号。

源代码(java)
代码片.

public  int minAddToMakeValid(String S) {
        char[] chars = S.toCharArray();
        int result = 0;
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < chars.length; i++) {
            //若栈为空,直接入栈
            if (stack.empty()) {
                stack.push(chars[i]);
            } else {
                //遇到左括号
                if (chars[i] == '(') {
                    //直接入栈
                    stack.push(chars[i]);

                    //判断栈顶是否有")"
                    if (stack.peek() == ')') {
                        //有就出栈,直到栈空或者栈顶元素不是")"
                        while (!stack.empty() && stack.peek() != ')') {
                            stack.pop();
                            result++;
                        }
                    }
                    //左括号入栈
                }
                //遇到右括号
                if (chars[i] == ')') {
                    //判断栈顶是否有"(",有就出栈
                    if (stack.peek() == '(') {
                        stack.pop();
                    }

                    //栈顶不是"(",右括号进栈
                    else {
                        stack.push(chars[i]);
                    }
                }
            }
        }
        //遍历栈内还有未匹配的括号
        while (!stack.empty()) {
            stack.pop();
            result++;
        }
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值