1249. Minimum Remove to Make Valid Parentheses - cocoder39/coco39_LC GitHub Wiki
1249. Minimum Remove to Make Valid Parentheses
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
for i, ch in enumerate(s):
if ch == '(':
stack.append(('(', i))
elif ch == ')':
if stack and stack[-1][0] == '(':
stack.pop()
else:
stack.append((')', i))
res = ''
cur = 0
for i, ch in enumerate(s):
if cur < len(stack) and i == stack[cur][1]:
cur += 1
else:
res += ch
return res