-
Notifications
You must be signed in to change notification settings - Fork 0
/
1249_Minimum_Remove_to_Make_Valid_Parentheses.py
90 lines (74 loc) · 2.55 KB
/
1249_Minimum_Remove_to_Make_Valid_Parentheses.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# 3 Possible Solutions
# 1. Using a Stack
# 2. Two Pass String Builder
# 3. Shortened Two Pass String Builder
class Solution:
# Time: O(N), Space: O(N)
def minRemoveToMakeValid(self, s: str) -> str:
indexesToRemove = set()
stack = []
for index, character in enumerate(s):
# Character is alpha, so skip
if character not in "()":
continue
# If character is opening parentheses
if character == "(":
stack.append(index)
# If character is closing parentheses and stack empty.
elif not stack:
indexesToRemove.add(index)
# If character is closing parentheses
else:
stack.pop()
indexesToRemove = indexesToRemove.union(set(stack))
stringBuilder = []
for idx, char in enumerate(s):
if idx not in indexesToRemove:
stringBuilder.append(char)
return "".join(stringBuilder)
# Time: O(N), Space: O(N)
def minRemoveToMakeValid(self, s: str) -> str:
firstPassChars = []
balance = 0
openParentheses = 0
for character in s:
if character == "(":
balance += 1
openParentheses += 1
if character == ")":
if balance == 0:
continue
balance -= 1
firstPassChars.append(character)
result = []
openToKeep = openParentheses - balance
for character in firstPassChars:
if character == "(":
openToKeep -= 1
if openToKeep < 0:
continue
result.append(character)
return "".join(result)
# Time: O(N), Space: O(N)
def minRemoveToMakeValid(self, s: str) -> str:
firstPass = []
balance = 0
openSeen = 0
for character in s:
if character == "(":
balance += 1
openSeen += 1
if character == ")":
if balance == 0:
continue
balance -= 1
firstPass.append(character)
result = []
openToKeep = openSeen - balance
for character in firstPass:
if character == "(":
openToKeep -= 1
if openToKeep < 0:
continue
result.append(character)
return "".join(result)