解題思路
此處撰寫解題思路
碰到左括號推入棧
碰到右括號時,把棧頂元素拿出來看是不是配對
遍歷完字符串棧不空表明有沒有被匹配的左括號
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