-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid_parenthesis.py
More file actions
49 lines (43 loc) · 1.35 KB
/
valid_parenthesis.py
File metadata and controls
49 lines (43 loc) · 1.35 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
# stack of characters
# push openning characters to top of stack
# when next character is closing, check is top
# of stack is the openning equivelant, if it is
# pop it
# if stack is empty at the end, it is valid
# list of openning characters
opening_chars = ['(', '{', '[']
# list of closing characters
closing_chars = [')', '}', ']']
# dictionary of characters
# key is openning, value is closing
chars = {
'(' : ')',
'{' : '}',
'[' : ']',
}
stack = []
for i in range(len(s)):
# if s[i] is an openning bracket (key in chars)
# push it to top of stack
if s[i] in chars:
stack.append(s[i])
# if the stack is not empty
# and
# if s[i] is the top of the stacks key, value
elif stack and s[i] == chars[stack[-1]]:
# pop it
stack.pop()
# otherwise it is not valid
else:
return False
# if stack isn't empty, its not valid
if stack:
return False
else:
return True