-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0020-valid-parenthesis.py
More file actions
35 lines (29 loc) · 987 Bytes
/
0020-valid-parenthesis.py
File metadata and controls
35 lines (29 loc) · 987 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
34
35
class Solution:
def isValid(self, s: str) -> bool:
# Check if string has equal numbers of open and closed parentheses
if (s.count('(') != s.count(')')) or (s.count('[') != s.count(']')) or (s.count('{') != s.count('}')):
return False
stack = []
for char in s:
# Put open parentheses in a stack
if char in ['(', '[', '{']:
stack.append(char)
# For every closed parenthesis, the last item on the stack should be its match
# Also catch any unapproved characters
else:
pair = stack.pop() + char
if pair not in ['()', '[]', '{}']:
return False
# Accept empty strings
return True
def main():
#input = "()"
input = "()[]d{}"
#input = "(]"
#input = "([)]"
#input = "{[]}"
#input = ""
sol = Solution()
print(sol.isValid(input))
if __name__ == "__main__":
main()