# 20. Valid Parentheses 有效的括号

## 刷题内容

• https://leetcode.com/problems/valid-parentheses
• https://leetcode-cn.com/problems/valid-parentheses

给定一个只包括 '('，')'，'{'，'}'，'['，']' 的字符串，判断字符串是否有效。



## 解题方案

• 出现右括号时stack里还有没有东西
• 出stack时是否对应
• 最终stack是否为空
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
leftP = '([{'
rightP = ')]}'
stack = []
for char in s:
if char in leftP:
stack.append(char)
if char in rightP:
if not stack:
return False
tmp = stack.pop()
if char == ')' and tmp != '(':
return False
if char == ']' and tmp != '[':
return False
if char == '}' and tmp != '{':
return False
return stack == []


• 扩展性和可理解性强
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) % 2 == 1:
return False

index = 0
stack = [i for i in s]
map1 = {"(": ")", "[": "]", "{": "}"}

while len(stack) > 0:
# 判断索引是否超过边界
if index >= len(stack)-1:
return False

b = stack[index]
e = stack[index+1]

if b not in map1.keys():
return False
elif e in map1.keys():
index += 1
elif map1[b] == e:
stack.pop(index+1)
stack.pop(index)
index = 0 if index-1<0 else index-1
else:
return False

return stack == []


apachecn/AiLearning