Use a stack.
class Solution:
MAPPING = {
'}': '{',
')': '(',
']': '['
}
def isValid(self, s: str) -> bool:
stack = []
for c in s:
if c in '({[':
stack.append(c)
elif c in ')}]':
if len(stack) == 0:
return False
if stack.pop() != self.MAPPING[c]:
return False
return len(stack) == 0