minimum remove to make valid parentheses

Go Back home
 1 class Solution(object):
 2     def minRemoveToMakeValid(self, s):
 3         stack = []
 4         invalid = []
 5         s = list(s)
 6         for i in range(len(s)):
 7             if s[i] == '(':
 8                 stack.append(i)
 9             if s[i] == ')':
10                 if stack:
11                     stack.pop()
12                 else:
13                     invalid.append(i)
14         
15         for i in invalid + stack:
16             s[i] = ''
17         
18         return ''.join(s)
19 
20 print(Solution().minRemoveToMakeValid('a(b'))