- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalid_parentheses.py
43 lines (32 loc) · 1.35 KB
/
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
classSolution:
defisValid(self, s: str) ->bool:
# main idea:
# A Last-In-First-Out (LIFO) data structure
# such as 'stack' is the perfect fit
iflen(s)==0:
returnTrue
valid_char= ['(', ')', '{', '}', '[', ']']
left_half= ['(', '[', '{']
right_half= [')', ']', '}']
# use a map/dictionary, which is more maintainable
another_half= {')': '(', '}':'{', ']':'['}
my_stack= []
forcharins:
ifcharnotinvalid_char:
returnFalse
# we see an opening parenthesis, we push it onto the stack
ifcharinleft_half:
my_stack.append(char)
# we encounter a closing parenthesis, we pop the last inserted opening parenthesis
ifcharinright_half:
iflen(my_stack) ==0:
returnFalse
# be careful: check if the pair is a valid match
elifanother_half[char] !=my_stack[len(my_stack)-1]:
returnFalse
else:
my_stack.pop()
iflen(my_stack) !=0:
returnFalse
else:
returnTrue