LeetCode 1249. Minimum Remove to Make Valid Parentheses解题报告(python)

1249. Minimum Remove to Make Valid Parentheses

  1. Minimum Remove to Make Valid Parentheses python solution

题目描述

Given a string s of ‘(’ , ‘)’ and lowercase English characters.
Your task is to remove the minimum number of parentheses ( ‘(’ or ‘)’, in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:
It is the empty string, contains only lowercase characters, 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.
在这里插入图片描述

解析

之前做过类似的题目,就是配对"(“和“)”。而且必须”("在“)”的前面出现。
需要对所有的括号进行判断,只有有效的括号才能被保留。

class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        stack=[]
        state_dict={}
        for idx, character in enumerate(s):
            if character=="(":
                stack.append(idx)
            if character==")" and len(stack)>0 :
                state_dict[idx]=True
                state_dict[stack[-1]]=True
                stack.pop()
                
        res=[]
        for idx, ch in enumerate(s):
            if ch=="(" or ch== ")":
                if idx in state_dict:res.append(ch)
            else:res.append(ch)
        
        return res
                

Reference

https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/419880/Simply-Simple-Python-Solution-with-comments

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值