Skip to content

Commit 31dc532

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 074e3c8 commit 31dc532

File tree

1 file changed

+43
-41
lines changed

1 file changed

+43
-41
lines changed

backtracking/Remove_Invalid_Parenthesis.py

+43-41
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,52 @@
11
def isParenthesis(c):
2-
return ((c == '(') or (c == ')'))
2+
return (c == "(") or (c == ")")
3+
34

45
def isValidString(str):
5-
cnt = 0
6-
for i in range(len(str)):
7-
if (str[i] == '('):
8-
cnt += 1
9-
elif (str[i] == ')'):
10-
cnt -= 1
11-
if (cnt < 0):
12-
return False
13-
return (cnt == 0)
14-
15-
# method to remove invalid parenthesis
6+
cnt = 0
7+
for i in range(len(str)):
8+
if str[i] == "(":
9+
cnt += 1
10+
elif str[i] == ")":
11+
cnt -= 1
12+
if cnt < 0:
13+
return False
14+
return cnt == 0
15+
16+
17+
# method to remove invalid parenthesis
1618
def removeInvalidParenthesis(str):
17-
if (len(str) == 0):
18-
return
19-
20-
visit = set()
21-
22-
q = []
23-
temp = 0
24-
level = 0
25-
26-
q.append(str)
27-
visit.add(str)
28-
while(len(q)):
29-
str = q[0]
30-
q.pop(0)
31-
if (isValidString(str)):
32-
print(str)
33-
34-
level = True
35-
if (level):
36-
continue
37-
for i in range(len(str)):
38-
if (not isParenthesis(str[i])):
39-
continue
40-
41-
temp = str[0:i] + str[i + 1:]
42-
if temp not in visit:
43-
q.append(temp)
44-
visit.add(temp)
19+
if len(str) == 0:
20+
return
21+
22+
visit = set()
23+
24+
q = []
25+
temp = 0
26+
level = 0
27+
28+
q.append(str)
29+
visit.add(str)
30+
while len(q):
31+
str = q[0]
32+
q.pop(0)
33+
if isValidString(str):
34+
print(str)
35+
36+
level = True
37+
if level:
38+
continue
39+
for i in range(len(str)):
40+
if not isParenthesis(str[i]):
41+
continue
42+
43+
temp = str[0:i] + str[i + 1 :]
44+
if temp not in visit:
45+
q.append(temp)
46+
visit.add(temp)
47+
4548

4649
expression = "()())()"
4750
removeInvalidParenthesis(expression)
4851
expression = "()v)"
4952
removeInvalidParenthesis(expression)
50-

0 commit comments

Comments
 (0)