Remove Invalid Parenthesis
Input:
"()())()"
Output:
["()()()", "(())()"]Input:
"(a)())()"
Output:
["(a)()()", "(a())()"]Input:")("
Output: [""]Last updated
Was this helpful?
Input:
"()())()"
Output:
["()()()", "(())()"]Input:
"(a)())()"
Output:
["(a)()()", "(a())()"]Input:")("
Output: [""]Last updated
Was this helpful?
Was this helpful?
class Solution:
def removeInvalidParentheses(self, s):
cnt = 0
idx = []
ans = ''
# forward to remove close first
for i, c in enumerate(s):
if c == '(':
cnt += 1
if c == ')':
cnt -= 1
if cnt < 0:
idx.append(i)
cnt = 0 # reset the cnt
cnt = 0
# reverse to remove open first
for i, c in enumerate(s[::-1]):
if c == ')':
cnt += 1
if c == '(':
cnt -= 1
if cnt < 0:
idx.append(len(s) - i - 1)
cnt = 0
return ''.join([s[i] for i in range(len(s)) if i not in idx])
s1= Solution()
print(s1.removeInvalidParentheses(""))
print(s1.removeInvalidParentheses("("))
print(s1.removeInvalidParentheses(")"))
print(s1.removeInvalidParentheses("(()"))
print(s1.removeInvalidParentheses("(()))"))class Solution:
def removeInvalidParentheses(self, s):
def isvalid(s):
ctr = 0
for c in s:
if c == '(':
ctr += 1
elif c == ')':
ctr -= 1
if ctr < 0:
return False
return ctr == 0
level = {s}
while True:
res = filter(isvalid, level)
if res:
return res
level = {s[:i] + s[i+1:] for s in level for i in range(len(s))}