LeetCode 1249. Minimum Remove to Make Valid Parentheses解题报告(python)
2020-01-14 12:31
489 查看
1249. Minimum Remove to Make Valid Parentheses
- 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
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- Leetcode 921 Minimum Add to Make Parentheses Valid
- LeetCode解题报告—— 4Sum & Remove Nth Node From End of List & Generate Parentheses
- LeetCode解题报告--Valid Parentheses
- [LeetCode] Valid Parentheses 解题报告
- 【LeetCode】20.Valid Parentheses解题报告
- LeetCode: Valid Parentheses 解题报告
- Leetcode 1190. Reverse Substrings Between Each Pair of Parentheses解题报告(python)
- 【LeetCode】Longest Valid Parentheses 解题报告
- LeetCode解题报告—— Longest Valid Parentheses
- [Leetcode] 20. Valid Parentheses 解题报告
- [leetcode] 32. Longest Valid Parentheses 解题报告
- [leetcode] 20. Valid Parentheses 解题报告
- LeetCode解题报告 241. Different Ways to Add Parentheses [medium]
- [LeetCode]Longest Valid Parentheses, 解题报告
- [LeetCode] Valid Parentheses 解题报告
- 【LeetCode】Valid Parentheses 解题报告
- [LeetCode] Longest Valid Parentheses 解题报告
- LeetCode 1247. Minimum Swaps to Make Strings Equals解题报告(python)
- [leetcode] 241. Different Ways to Add Parentheses 解题报告
- Leetcode Valid Parentheses 解题报告