标签:ima code style 提交 flag com counter turn nbsp
题目描述:
自己的提交: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)
标签:ima code style 提交 flag com counter turn nbsp
原文地址:https://www.cnblogs.com/oldby/p/11790985.html