-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid_parentheses.py
More file actions
34 lines (28 loc) · 891 Bytes
/
valid_parentheses.py
File metadata and controls
34 lines (28 loc) · 891 Bytes
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
class Solution:
PARENTHESES_MAP = {
"(": ")",
"[": "]",
"{": "}"
}
def isValid(self, s: str) -> bool:
return self.solution_1(s)
def solution_1(self, s: str) -> bool:
stack = []
if len(s) <= 1: # cannot be true right?
return False
for p in s:
is_opening = p in self.PARENTHESES_MAP
if is_opening:
stack.append(p)
continue
# we are working with a closing one
if not stack:
return False
next_opened = stack.pop()
expected_closed = self.PARENTHESES_MAP.get(next_opened, None) == p
if not expected_closed:
return False
# if we got something left means some parenthesis isn't closed
if stack:
return False
return True