解题思路
此处撰写解题思路
碰到左括号推入栈
碰到右括号时,把栈顶元素拿出来看是不是配对
遍历完字符串栈不空表明有没有被匹配的左括号
https://leetcode-cn.com/problems/valid-parentheses/
代码
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
match = {
'}': '{',
']': '[',
')': '(',
}
stack = []
idx, length = 0, len(s)
while idx < length:
if s[idx] in '([{':
stack.append(s[idx])
idx += 1
else:
if not stack:
return False
elif stack.pop() != match[s[idx]]:
return False
else:
idx += 1
return len(stack) == 0