leetcode/0020_valid-parentheses/python3/solution.py

31 lines
774 B
Python

from collections import deque
class Solution:
bracket_pairing = {
'{': '}',
'[': ']',
'(': ')'
}
closing_brackets = tuple(bracket_pairing.values())
def is_matching_pair(self, opening, closing):
return self.bracket_pairing[opening] == closing
def isValid(self, s: str) -> bool:
stack = deque()
for c in s:
if c in self.closing_brackets:
try:
last_char = stack.pop()
except IndexError:
return False
if not self.is_matching_pair(last_char, c):
return False
else:
stack.append(c)
return len(stack) == 0