-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path020 Valid Parentheses.py
More file actions
33 lines (25 loc) · 972 Bytes
/
020 Valid Parentheses.py
File metadata and controls
33 lines (25 loc) · 972 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
"""
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Author : Rajeev Ranjan
"""
class Solution:
def isValid(self, s):
"""
Algorithm: Stack
:param s: string
:return: boolean
"""
put_set = ("(", "[", "{")
pop_set = (")", "]", "}")
pair = dict(zip(put_set, pop_set))
stack = []
for element in s:
if element in put_set:
stack.append(pair[element])
elif element in pop_set:
if not stack or element != stack.pop(): # check NullPointer, otherwise, IndexError: pop from empty list
return False
return True if not stack else False
if __name__ == "__main__":
assert Solution().isValid("()")