Skip to content

Commit 2e7fb2e

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 20 Valid Parentheses
1 parent f898842 commit 2e7fb2e

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
2525
## Leetcode Problems & Solutions 💻
2626

2727
- [1 Two Sum](https://leetcode.com/problems/two-sum/description/)
28+
- [20 Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/)
2829
- [26 Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/)
2930
- [27 Remove Element](https://leetcode.com/problems/remove-element/description/)
3031
- [45 Jump Game II](https://leetcode.com/problems/jump-game-ii/description/)
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution:
2+
def isValid(self, s: str) -> bool:
3+
"""
4+
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
5+
determine if the input string is valid.
6+
7+
An input string is valid if:
8+
1. Open brackets must be closed by the same type of brackets.
9+
2. Open brackets must be closed in the correct order.
10+
3. Every close bracket has a corresponding open bracket of the same type.
11+
"""
12+
brackets = {"(": ")", "{": "}", "[": "]"}
13+
stack = []
14+
for bracket in s:
15+
if bracket in brackets:
16+
stack.append(bracket)
17+
elif not stack:
18+
return False
19+
else:
20+
open_bracket = stack.pop()
21+
closed_bracket = brackets[open_bracket]
22+
if closed_bracket != bracket:
23+
return False
24+
return not stack

tests/test_20_valid_parentheses.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import pytest
2+
3+
from awesome_python_leetcode._20_valid_parentheses import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
argnames=["s", "expected"],
8+
argvalues=[
9+
("()", True),
10+
("()[]{}", True),
11+
("(]", False),
12+
("([])", True),
13+
],
14+
)
15+
def test_func(s: str, expected: bool):
16+
is_valid = Solution().isValid(s)
17+
assert is_valid == expected

0 commit comments

Comments
 (0)