-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20_valid_parentheses_stack.py
More file actions
32 lines (29 loc) · 1019 Bytes
/
20_valid_parentheses_stack.py
File metadata and controls
32 lines (29 loc) · 1019 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
"""
Topics:
- stack
O(N), efficient implementation
"""
class Solution:
def isValid(self, s: str) -> bool:
close_to_open = {
"}":"{",
"]":"[",
")":"(",
}
stack = []
for i, char in enumerate(s):
if char in close_to_open: # if closing char
# check matches last in stack
if stack and stack[-1] == close_to_open[char]:
stack.pop() # if match, remove from stack
else:
return False # if not match, string invalid because
# parentheses in wrong order
else: # if not closing char, add to stack
stack.append(char)
# if anything left in stack, False bc parentheses weren't closed
return True if not stack else False
solution = Solution()
print(solution.isValid("{[]}")) # true
print(solution.isValid("[(])")) # false
print(solution.isValid("(){}[]")) # true