-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20_Valid_Parentheses.py
More file actions
26 lines (23 loc) · 1.18 KB
/
20_Valid_Parentheses.py
File metadata and controls
26 lines (23 loc) · 1.18 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
class Solution:
# Time: O(N), Space: O(N)
def isValid(self, s: str) -> bool:
# Empty stack needed to keep track of open brackets
stack = []
# Dictionary required to keep track of a closing bracket against a matching open brakcet
bracketDictionary = {")": "(", "}": "{", "]": "["}
# For every bracket in the expression
for character in s:
# Pop the topmost element from the stack, if it is non empty
# Otherwise assign a dummy value of '#' to the top_element variable
if character in bracketDictionary:
top_element = stack.pop() if stack else '#'
# The mapping for the opening bracket in our hash and the top
# element of the stack don't match, return False
if bracketDictionary[character] != top_element:
return False
else:
# We have an opening bracket, simply push it onto the stack.
stack.append(character)
# In the end, if the stack is empty, then we have a valid expression.
# The stack won't be empty for cases like ((()
return not stack