""" 0020.1 - Valid Parentheses - Solution 1 - Stack with Mapped Closing Brackets """
#####################################################################################
# Imports
#####################################################################################
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def isValid(self, s: str) -> bool:
"""Valid Parentheses Function"""
stack = []
for c in s:
if c == '(':
stack.append(')')
elif c == '{':
stack.append('}')
elif c == '[':
stack.append(']')
elif not stack or stack.pop() != c:
return False
return not stack
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().isValid("()")) # True
print(Solution().isValid("()[]{}")) # True
print(Solution().isValid("(]")) # False
print(Solution().isValid("([])")) # True
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()
""" 0020.2 - Valid Parentheses - Solution 2 - Stack with Dictionary Lookup """
#####################################################################################
# Imports
#####################################################################################
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def isValid(self, s: str) -> bool:
"""Valid Parentheses Function"""
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for c in s:
if c in mapping:
top = stack.pop() if stack else '#'
if mapping[c] != top:
return False
else:
stack.append(c)
return not stack
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().isValid("()")) # True
print(Solution().isValid("()[]{}")) # True
print(Solution().isValid("(]")) # False
print(Solution().isValid("([])")) # True
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()