Skip to content

Commit 45704a7

Browse files
Python solution for problem # 20 (#5)
new solution and readme update Co-authored-by: Yuri <[email protected]>
1 parent 0bf0324 commit 45704a7

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

Python/20_ValidParentheses.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# -*- coding: utf-8 -*-
2+
#Difficulty: Easy
3+
#Runtime: 82.23%
4+
#Memory Usage: 64.83%
5+
6+
"""
7+
Algorithm:
8+
1. Check a bracket (b) in the string (s), if it contains in parentheses
9+
dictionary then we add to stack it's opposite bracket.
10+
2. If bracket not in parentheses we check does it mach with last bracket in
11+
the stack, also we check if stack exists while iterating through the string.
12+
If one of this conditions is not True - return False immediately.
13+
3. After we checked whole string we need to check is stack empty or not and
14+
return result.
15+
4. Result will be true if stack is empty it means all parentheses are valid
16+
and closed in the correct order.
17+
18+
Time Complexity = O(n)
19+
Space Complexity = O(n)
20+
"""
21+
22+
class Solution:
23+
def isValid(self, s: str) -> bool:
24+
parentheses = {'(':')', '{':'}', '[':']'}
25+
stack = []
26+
for b in s: # take bracket 'b' from string 's'
27+
if b in parentheses: # if bracket in parentheses
28+
stack.append(parentheses[b]) # append it's opposite to stack
29+
elif not stack or stack.pop() != b: # if not stack or bracket not
30+
return False # equal last bracket in stack
31+
return not stack # if stack still exists -> False else True

README.md

+12
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,18 @@
100100
</div>
101101
<br/>
102102

103+
## Stack
104+
| # | Title | Solution | Time | Space | Difficulty | Tag | Note|
105+
|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----|
106+
|020|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)|[Python](./Python/20_ValidParentheses.py)|_O(n)_|_O(n)_|Easy|Stack||
107+
108+
<br/>
109+
<div align="right">
110+
<b><a href="#algorithms">⬆️ Back to Top</a></b>
111+
</div>
112+
<br/>
113+
114+
103115
## Graph
104116
| # | Title | Solution | Time | Space | Difficulty | Tag | Note|
105117
|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----|

0 commit comments

Comments
 (0)