-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20_valid_parenthesis.py
More file actions
30 lines (28 loc) · 916 Bytes
/
20_valid_parenthesis.py
File metadata and controls
30 lines (28 loc) · 916 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
'''
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.
'''
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for c in s:
if c == '(' or c =='{' or c == '[':
stack.append(c)
else:
if len(stack) == 0:
return False
d = stack[-1]
del stack[-1]
if c == ')' and d != '(':
return False
if c == ']' and d != '[':
return False
if c == '}' and d != '{':
return False
if len(stack) == 0:
return True
return False