mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-04-21 21:27:36 +00:00
Remove_Invalid_Parenthesis.py
This commit is contained in:
parent
52602ea5b6
commit
074e3c8732
50
backtracking/Remove_Invalid_Parenthesis.py
Normal file
50
backtracking/Remove_Invalid_Parenthesis.py
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
def isParenthesis(c):
|
||||||
|
return ((c == '(') or (c == ')'))
|
||||||
|
|
||||||
|
def isValidString(str):
|
||||||
|
cnt = 0
|
||||||
|
for i in range(len(str)):
|
||||||
|
if (str[i] == '('):
|
||||||
|
cnt += 1
|
||||||
|
elif (str[i] == ')'):
|
||||||
|
cnt -= 1
|
||||||
|
if (cnt < 0):
|
||||||
|
return False
|
||||||
|
return (cnt == 0)
|
||||||
|
|
||||||
|
# method to remove invalid parenthesis
|
||||||
|
def removeInvalidParenthesis(str):
|
||||||
|
if (len(str) == 0):
|
||||||
|
return
|
||||||
|
|
||||||
|
visit = set()
|
||||||
|
|
||||||
|
q = []
|
||||||
|
temp = 0
|
||||||
|
level = 0
|
||||||
|
|
||||||
|
q.append(str)
|
||||||
|
visit.add(str)
|
||||||
|
while(len(q)):
|
||||||
|
str = q[0]
|
||||||
|
q.pop(0)
|
||||||
|
if (isValidString(str)):
|
||||||
|
print(str)
|
||||||
|
|
||||||
|
level = True
|
||||||
|
if (level):
|
||||||
|
continue
|
||||||
|
for i in range(len(str)):
|
||||||
|
if (not isParenthesis(str[i])):
|
||||||
|
continue
|
||||||
|
|
||||||
|
temp = str[0:i] + str[i + 1:]
|
||||||
|
if temp not in visit:
|
||||||
|
q.append(temp)
|
||||||
|
visit.add(temp)
|
||||||
|
|
||||||
|
expression = "()())()"
|
||||||
|
removeInvalidParenthesis(expression)
|
||||||
|
expression = "()v)"
|
||||||
|
removeInvalidParenthesis(expression)
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user