Skip to content

Commit 18c139f

Browse files
committedNov 4, 2020
feat: valid-parentheses
1 parent 8b24fa3 commit 18c139f

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
 

‎stack.valid-parentheses.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution:
2+
"""
3+
20. 有效的括号
4+
https://leetcode-cn.com/problems/valid-parentheses/
5+
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
6+
有效字符串需满足:
7+
左括号必须用相同类型的右括号闭合。
8+
左括号必须以正确的顺序闭合。
9+
注意空字符串可被认为是有效字符串。
10+
"""
11+
# 栈: 将不同括号分为左右两边,只要是左边则进栈,遇到右边则看是否与栈顶元素匹配。O(n)时间复杂度
12+
def isValid(self, s: str) -> bool:
13+
# 如果长度为奇数,则不满足
14+
if len(s) % 2 != 0:
15+
return False
16+
17+
pairs = {
18+
'{': '}',
19+
'[': ']',
20+
'(': ')'
21+
}
22+
stack = list()
23+
for c in s:
24+
if c in pairs:
25+
stack.append(c)
26+
elif len(stack) > 0 and pairs[stack[-1]] == c:
27+
stack.pop(-1)
28+
else:
29+
return False
30+
31+
return not stack
32+
33+
# 暴力破解:通过不断循环清除最小单元,直到没有最小单元,如果剩余字符串长度为0,则满足条件
34+
def isValidByForce(self, s: str) -> bool:
35+
while len(s) > 0:
36+
s = s.replace('()', '').replace('[]', '').replace('{}', '')
37+
if s.find('{}') == -1 and s.find('[]') == -1 and s.find('()') == -1:
38+
break
39+
40+
return len(s) == 0
41+
42+
43+
so = Solution()
44+
print(so.isValid('()[]{}'))
45+
print(so.isValid('([)]{}'))

0 commit comments

Comments
 (0)