File tree 2 files changed +43
-0
lines changed
2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change 100
100
</div >
101
101
<br />
102
102
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
+
103
115
## Graph
104
116
| # | Title | Solution | Time | Space | Difficulty | Tag | Note|
105
117
| -----| ---------------- | --------------- | --------------- | --------------- | ------------- | --------------| -----|
You can’t perform that action at this time.
0 commit comments