-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path20. Valid Parentheses.py
51 lines (40 loc) · 1.26 KB
/
20. 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for val in s:
if val == '{' or val == '(' or val == '[':
stack.append(val)
continue
elif len(stack) == 0:
return False
top_stak = stack.pop()
if (top_stak == '{' and val != '}') or (top_stak == '(' and val != ')') or (top_stak == '[' and val != ']'):
return False
return len(stack) == 0
sol = Solution()
s = "{[]}"
boo = sol.isValid(s)
print(boo)
"""
See how similar is the best solution!!
Uses the list of values an the function "in"
class Solution:
def isValid(self, s: str) -> bool:
stack = []
o_brackets = ['(', '[', '{']
c_brackets = [')', ']', '}']
for c in s:
if c in o_brackets:
stack.append(c)
if c in c_brackets:
if not stack:
return False
last_bracket = stack.pop()
if (
c == ')' and last_bracket != '(' or
c == '}' and last_bracket != '{' or
c == ']' and last_bracket != '['
):
return False
return len(stack) == 0
"""