MCPcopy
hub / github.com/keon/algorithms / is_valid

Function is_valid

algorithms/stack/valid_parenthesis.py:17–39  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

15
16
17def 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

Callers 1

Calls 1

popMethod · 0.45

Tested by 1