leetcode-161周赛-5249-移除无效的括号
Posted 真不知道叫啥好
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-161周赛-5249-移除无效的括号相关的知识,希望对你有一定的参考价值。
题目描述:
自己的提交:O(N)
class Solution: def minRemoveToMakeValid(self, s: str) -> str: #from collections import Counter flag = [True] * len(s) stack = [] for i,v in enumerate(s): if v == "(": stack.append(i) flag[i] = False if v == ")": if stack: flag[stack.pop()] = True else: flag[i] = False res = "" for i in range(len(s)): if flag[i] == True: res += s[i] return res
优化:
class Solution: def minRemoveToMakeValid(self, s: str) -> str: pos = set() stk = [] for i, ch in enumerate(s): if s[i] == \'(\': stk.append(i) elif s[i] == \')\': if len(stk) == 0: pos.add(i) else: stk.pop() for p in stk: pos.add(p) ans = [] for i, ch in enumerate(s): if i not in pos: ans.append(ch) return "".join(ans)
以上是关于leetcode-161周赛-5249-移除无效的括号的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode(周赛):移除字母异位词5234,最大连续楼层数6064