【Leetcode】【python】Valid Parentheses

题目大意

判断括号开闭

解题思路

简单题,思路正确即可

代码

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
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for char in s:
if char == '(' or char == '{' or char == '[':
stack.append(char)
continue
elif char == ')':
temp = '('
elif char == '}':
temp = '{'
elif char == ']':
temp = '['
else:
return False

if stack:
if stack[-1] == temp:
stack.pop()
else:
return False
else:
return False

if len(stack) != 0:
return False
return True

由于pop()时会输出pop的数值,所以可以简化:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
# @return a boolean
def isValid(self, s):
stack = []
for i in range(len(s)):
if s[i] == '(' or s[i] == '[' or s[i] == '{':
stack.append(s[i])
if s[i] == ')':
if stack == [] or stack.pop() != '(':
return False
if s[i] == ']':
if stack == [] or stack.pop() != '[':
return False
if s[i] == '}':
if stack == [] or stack.pop() != '{':
return False
if stack:
return False
else:
return True

总结