-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidParentheses.py
More file actions
27 lines (22 loc) · 836 Bytes
/
Copy pathvalidParentheses.py
File metadata and controls
27 lines (22 loc) · 836 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
# Stack
# logic flow:
# check if close bracket matches open bracket in the hash map => yes => pop it out
# stack is empty => all matches in the correct order => return true
class Solution:
def isValid(self, s: str) -> bool:
stack = []
closeToOpenPairs = {"]":"[","}":"{", ")":"("}
for char in s:
if char in closeToOpenPairs:
# check if stack is not empty & does the top match what we need
if stack and stack[-1] == closeToOpenPairs[char]:
stack.pop()
else:
return False
else:
stack.append(char)
return True if not stack else False
sol = Solution()
assert sol.isValid(s = "([{}])") == True
assert sol.isValid(s = "[(])") == False
print("All tests are passed")