-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathminimum-add-to-make-parentheses-valid.py
More file actions
48 lines (35 loc) · 1.17 KB
/
minimum-add-to-make-parentheses-valid.py
File metadata and controls
48 lines (35 loc) · 1.17 KB
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
import uniitest
# All the solutions run in exactly the same time, but stack requires a
# little bit more memory
class Solution:
def minAddToMakeValidStack(self, S: str) -> int:
stack = []
for s in S:
if len(stack) and s == ")" and stack[-1] == "(":
stack.pop()
else:
stack.append(s)
return len(stack)
def minAddToMakeValid(self, S: str) -> int:
balance = 0
answer = 0
for s in S:
if s == ")":
balance -= 1
else:
balance += 1
if balance == -1:
balance = 0
answer += 1
return answer + balance
class TestSolution(unittest.TestCase):
def setUp(self):
self.sol = Solution()
def test(self):
self.assertEqual(self.sol.minAddToMakeValid(""), 0)
self.assertEqual(self.sol.minAddToMakeValid("())"), 1)
self.assertEqual(self.sol.minAddToMakeValid("((("), 3)
self.assertEqual(self.sol.minAddToMakeValid("()"), 0)
self.assertEqual(self.sol.minAddToMakeValid("()))(("), 4)
if __name__ == "__main__":
unittest.main()