""" 0020.1 - Valid Parentheses - Solution 1 - Stack """
#####################################################################################
# Imports
#####################################################################################
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def isValid(self, s: str) -> bool:
"""Valid Parentheses Function"""
stack = []
mapping = {")": "(", "}": "{", "]": "["}
for char in s:
if char in mapping:
top = stack.pop() if stack else "#"
if mapping[char] != top:
return False
else:
stack.append(char)
return not stack
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().isValid("()")) # True
print(Solution().isValid("()[]{}")) # True
print(Solution().isValid("(]")) # False
print(Solution().isValid("([])")) # True
print(Solution().isValid("")]")) # False
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()
""" 0020.2 - Valid Parentheses - Solution 2 - Stack using Enumerate """
#####################################################################################
# Imports
#####################################################################################
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def isValid(self, s: str) -> bool:
"""Valid Parentheses Function"""
stack = []
open_brackets = {"(", "{", "["}
close_to_open = {")": "(", "}": "{", "]": "["}
for idx, char in enumerate(s):
if char in open_brackets:
stack.append(char)
elif char in close_to_open:
if not stack or stack[-1] != close_to_open[char]:
return False
stack.pop()
return len(stack) == 0
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().isValid("()")) # True
print(Solution().isValid("()[]{}")) # True
print(Solution().isValid("(]")) # False
print(Solution().isValid("([])")) # True
print(Solution().isValid("")]")) # False
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()