-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path020_Valid_Parentheses.py
32 lines (28 loc) · 1.06 KB
/
020_Valid_Parentheses.py
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
"""
https://leetcode.com/problems/valid-parentheses/
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__ = 'abhireddy96'
class Solution:
def isValid(self, s: str) -> bool:
# Hash map of closing and opening parenthesis
d = {')': '(', ']': '[', '}': '{'}
ls = []
# Iterate over string
for i in s:
# Check if it is closing parenthesis
if i in d:
# If so, pop top element from stack
sym = ls.pop() if ls else ''
# Compare if parenthesis of same type
# If not immediately return False
if d[i] != sym:
return False
# Check if it is opening parenthesis
# Add it to stack
else:
ls.append(i)
return ls == []
if __name__ == "__main__":
print(Solution().isValid("{[]}"))