LeetCode 921. Minimum Add to Make Parentheses Valid解题报告

探讨了如何通过最小次数的括号添加使给定的括号字符串变为有效。算法解析了左括号与右括号的匹配过程,计算额外所需括号数量。

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

921. Minimum Add to Make Parentheses Valid

  1. Minimum Add to Make Parentheses Valid python solution

题目描述

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.
在这里插入图片描述

解析

需要找出’(‘和’)‘的对应关系,记录连续出现’(‘的次数,若此时出现‘)’,就说明有()配对。计算在’(‘后‘)’多出现的次数,同理记录在‘)’后’('多出现的次数。两者的绝对值之和,就是需要添加的个数。

// An highlighted block
class Solution:
    def minAddToMakeValid(self, S: str) -> int:
        left=0
        right=0
        for i in S:
            if i=='(':
                left+=1
            elif left>=1:
                left-=1
            else: right+=1
        
        return left+right

Reference

https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/420068/python-without-stack-beats-99

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值