Check if the bracket string is valid. Args: s: A string containing only bracket characters. Returns: True if the brackets are valid, False otherwise. Examples: >>> is_valid("()[]{}") True >>> is_valid("(]") False
(s: str)
| 15 | |
| 16 | |
| 17 | def is_valid(s: str) -> bool: |
| 18 | """Check if the bracket string is valid. |
| 19 | |
| 20 | Args: |
| 21 | s: A string containing only bracket characters. |
| 22 | |
| 23 | Returns: |
| 24 | True if the brackets are valid, False otherwise. |
| 25 | |
| 26 | Examples: |
| 27 | >>> is_valid("()[]{}") |
| 28 | True |
| 29 | >>> is_valid("(]") |
| 30 | False |
| 31 | """ |
| 32 | stack: list[str] = [] |
| 33 | matching = {")": "(", "}": "{", "]": "["} |
| 34 | for char in s: |
| 35 | if char in matching.values(): |
| 36 | stack.append(char) |
| 37 | elif char in matching and (not stack or matching[char] != stack.pop()): |
| 38 | return False |
| 39 | return not stack |