-
Notifications
You must be signed in to change notification settings - Fork 0
/
letcode_20_有效的括号.py
74 lines (65 loc) · 1.68 KB
/
letcode_20_有效的括号.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@File:letcode_20_有效的括号.py
@Data:2019/7/23
@param:
@return:
"""
class Solution:
def match(self, s1, s2) -> bool:
if s1 == '(' and s2 == ')':
return True
if s1 == '[' and s2 == ']':
return True
if s1 == '{' and s2 == '}':
return True
else:
return False
def isValid(self, s: str) -> bool:
s_len = len(s)
if s_len % 2 != 0 or " " in s:
return False
if s_len == 0:
return True
mj = []
mj.append(s[0])
if s[0] == ']' or s[0] == '}' or s[0] == ')':
return False
for i in range(1, s_len):
if s[i] == '[' or s[i] == '{' or s[i] == '(':
mj.append(s[i])
continue
if self.match(mj[len(mj) - 1], s[i]):
mj.pop()
else:
return False
if mj:
return False
else:
return True
# 优化代码
class Solutions:
def isValid(self, s: str) -> bool:
dic = {'(': ')', '[': ']', '{': '}'}
s_len = len(s)
if s_len == 0:
return True
if s_len % 2 != 0 or s[0] not in dic:
return False
mj = []
for value in s:
if value in dic:
mj.append(value)
else:
# -1指最后一个元素
if dic[mj[-1]] == value:
mj.pop()
continue
else:
return False
if mj:
return False
else:
return True