Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: “()”
Output: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
# use list for stack to keep track of openning brackets
stack = []
# use Hash Map for keeping track of mapping (對應關係). Keeps code clean
# Also easier to add more types of parenthesis
# key is right bracket, value is left bracket
mapping = {")": "(", "]": "[", "}": "{"}
for char in s:
# If the character is an right or closing bracket
if char in mapping:
# pop the topMost element from the stack if it is not empty
# if it's empty, assign a dummy value for later comparison.
topElement = stack.pop() if stack else '!'
# if the topElement is not equal to the char corresponding value (left bracket), return False
if mapping[char] != topElement:
return False
else:
# push the left bracket onto the stack
stack.append(char)
# In the end, if the stack is empty, then we have a valid expression
# If not empty, then notValid.
return not stack```