Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
, and ']'
, determine if the input string is valid. An input string is valid if:
Stack and Hash Map
matching_pairs
to map each closing bracket to its corresponding opening bracket.matching_pairs
):
False
.True
(all opening brackets were matched correctly). Otherwise, return False
.class Solution:
def isValid(self, s: str) -> bool:
stack = []
matching_pairs = {')': '(', '}': '{', ']': '['}
for char in s:
if char in matching_pairs:
if not stack or stack[-1] != matching_pairs[char]:
return False
stack.pop()
else:
stack.append(char)
return not stack