-
Notifications
You must be signed in to change notification settings - Fork 0
/
020_is_valid.py
38 lines (35 loc) · 1011 Bytes
/
020_is_valid.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
class Solution(object):
def is_valid(self, s):
"""
:type s: str
:rtype: bool
"""
match_dict = {'(': ')',
'[': ']',
'{': '}'}
stack = []
for char in s:
if char in match_dict.keys():
stack.append(char)
else:
if stack and char == match_dict[stack[-1]]:
stack.pop()
else:
return False
return not stack
# if stack:
# return False
# return True
def is_valid_2(self, s):
stack = []
match_dict = {')': '(',
']': '[',
'}': '{'}
for char in s:
if char in match_dict:
ele_top = stack.pop() if stack else '#'
if ele_top != match_dict[char]:
return False
else:
stack.append(char)
return not stack