diff --git a/LeetCode/easy/is_valid_20.py b/LeetCode/easy/is_valid_20.py new file mode 100644 index 0000000..ab7ece4 --- /dev/null +++ b/LeetCode/easy/is_valid_20.py @@ -0,0 +1,17 @@ +class Solution: + def isValid(self, s: str) -> bool: + p_map = {")": "(", "}": "{", "]": "["} + stack = [] + + for i in s: + if i in p_map: + if not stack: + return False + elif stack[-1] == p_map[i]: + stack.pop() + else: + return False + else: + stack.append(i) + + return len(stack) == 0 diff --git a/tests/test_leetcode.py b/tests/test_leetcode.py index a6d07d1..a3a9914 100644 --- a/tests/test_leetcode.py +++ b/tests/test_leetcode.py @@ -269,14 +269,18 @@ def test_reverse_integer(x: int, expected: int): (")", False), # Single closing parenthesis ("(((((((((())))))))))", True), # Deeply nested ("(((((((((()))", False), # Deeply nested but incomplete + (")(", False), ], ) def test_is_valid_parentheses(s: str, expected: bool): + from LeetCode.easy.is_valid_20 import Solution as Sol from LeetCode.valid_parentheses_20 import Solution solution = Solution() result = solution.isValid(s) + res = Sol().isValid(s) assert result == expected + assert res == expected, f'expected {expected} but got {res} for "{s}"' @pytest.mark.parametrize(