File tree Expand file tree Collapse file tree 2 files changed +36
-32
lines changed Expand file tree Collapse file tree 2 files changed +36
-32
lines changed Original file line number Diff line number Diff line change 1111<p >  ; </p >
1212<p ><strong class =" example " >Example 1:</strong ></p >
1313
14- <pre >
15- <strong >Input:</strong > s = " ; ()" ;
16- <strong >Output:</strong > true
17- </pre >
14+ <div class =" example-block " >
15+ <p ><strong >Input:</strong > <span class =" example-io " >s = " ; ()" ; </span ></p >
16+
17+ <p ><strong >Output:</strong > <span class =" example-io " >true</span ></p >
18+ </div >
1819
1920<p ><strong class =" example " >Example 2:</strong ></p >
2021
21- <pre >
22- <strong >Input:</strong > s = " ; ()[]{}" ;
23- <strong >Output:</strong > true
24- </pre >
22+ <div class =" example-block " >
23+ <p ><strong >Input:</strong > <span class =" example-io " >s = " ; ()[]{}" ; </span ></p >
24+
25+ <p ><strong >Output:</strong > <span class =" example-io " >true</span ></p >
26+ </div >
2527
2628<p ><strong class =" example " >Example 3:</strong ></p >
2729
28- <pre >
29- <strong >Input:</strong > s = " ; (]" ;
30- <strong >Output:</strong > false
31- </pre >
30+ <div class =" example-block " >
31+ <p ><strong >Input:</strong > <span class =" example-io " >s = " ; (]" ; </span ></p >
32+
33+ <p ><strong >Output:</strong > <span class =" example-io " >false</span ></p >
34+ </div >
35+
36+ <p ><strong class =" example " >Example 4:</strong ></p >
37+
38+ <div class =" example-block " >
39+ <p ><strong >Input:</strong > <span class =" example-io " >s = " ; ([])" ; </span ></p >
40+
41+ <p ><strong >Output:</strong > <span class =" example-io " >true</span ></p >
42+ </div >
3243
3344<p >  ; </p >
3445<p ><strong >Constraints:</strong ></p >
Original file line number Diff line number Diff line change 1- # Approach 1 - Stack
1+ # Approach 1: Stacks
22
33# Time: O(n)
44# Space: O(n)
55
66class Solution :
77 def isValid (self , s : str ) -> bool :
88 stack = []
9-
10- mappings = {')' : '(' ,
11- ']' :'[' ,
12- '}' :'{' }
13-
14- for char in s :
15- # check if is it closing bracket
16- if char in mappings :
17-
18- # popping the last opening bracket, closing bracket is never pushed to the stack
19- last_element = stack .pop () if stack else '#'
20-
21- if mappings [char ] != last_element :
22- return False
23-
24- # its char in opening bracket, append to stack
9+
10+ mapping = {')' : "(" , '}' : '{' , ']' : '[' }
11+
12+ for char in s :
13+ if char in mapping :
14+ top_element = stack .pop () if stack else '#'
15+
16+ if mapping [char ] != top_element :
17+ return False
2518 else :
26- stack .append (char )
27-
28- # if still there are elements in the stack, then return False
19+ stack .append (char )
20+
2921 return not stack
22+
You can’t perform that action at this time.
0 commit comments