leetcode-study

20. Valid Parentheses

class Solution:
    def isValid(self, s: str) -> bool:
        """
        Determine if the string 's' with brackets is valid.
        
        A string is valid if:
         - All open brackets are closed by the same type of brackets.
         - Open brackets are closed in the correct order.
         - Every closing bracket has a corresponding opening bracket.
        
        Parameters:
            s (str): A string comprised of the characters '(', ')', '{', '}', '[' and ']'.
        
        Returns:
            bool: True if the string is valid, False otherwise.
        """
        # Map closing brackets to their corresponding opening brackets.
        bracket_map = {')': '(', '}': '{', ']': '['}
        # Initialize an empty stack to keep track of encountered opening brackets.
        stack = []
        
        # Process each character in the input string.
        for char in s:
            if char in bracket_map:
                # For each closing bracket, pop the top element from the stack if available.
                top_element = stack.pop() if stack else '#'
                # If the popped element does not match the corresponding opening bracket, the string is invalid.
                if bracket_map[char] != top_element:
                    return False
            else:
                # Push opening brackets onto the stack.
                stack.append(char)
                
        # If the stack is empty, all brackets were correctly matched.
        return not stack

Summary of Techniques and Approaches: