-
Notifications
You must be signed in to change notification settings - Fork 612
/
301.py
63 lines (50 loc) · 1.38 KB
/
301.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'''
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Example 1:
Input: "()())()"
Output: ["()()()", "(())()"]
Example 2:
Input: "(a)())()"
Output: ["(a)()()", "(a())()"]
Example 3:
Input: ")("
Output: [""]
'''
class Solution(object):
def removeInvalidParentheses(self, s):
"""
:type s: str
:rtype: List[str]
"""
if not s:
return [""]
def isValid(s):
count = 0
for char in s:
if char == '(':
count += 1
elif char == ')':
count -= 1
if count < 0:
return False
return (count==0)
queue, result = [s], []
visited = set()
visited.add(s)
level = False
while queue:
new_str = queue.pop(0)
if isValid(new_str):
result.append(new_str)
level = True
if level:
continue
for index in range(len(new_str)):
if not (new_str[index] == "(" or new_str[index] == ")"):
continue
partition_str = new_str[0:index] + new_str[index+1:]
if partition_str not in visited:
queue.append(partition_str)
visited.add(partition_str)
return result