File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Problem: https://leetcode.com/problems/valid-parentheses/
2
+ // Doc: https://leetcode.com/problems/valid-parentheses/solutions/5491623/efficient-solution-for-valid-parentheses/
3
+ const isValid = ( s : string ) : boolean => {
4
+ const stack : string [ ] = [ ] ;
5
+
6
+ const parClosedMap = {
7
+ ')' : '(' ,
8
+ '}' : '{' ,
9
+ ']' : '[' ,
10
+ } ;
11
+
12
+ for ( let i = 0 ; i < s . length ; i ++ ) {
13
+ const char = s [ i ] ;
14
+ if ( ! ( char in parClosedMap ) ) {
15
+ stack . push ( char ) ;
16
+ continue ;
17
+ }
18
+
19
+ const popped = stack . pop ( ) ;
20
+ if ( ! popped ) return false ;
21
+ const opened = parClosedMap [ char ] ;
22
+ if ( popped !== opened ) return false ;
23
+ }
24
+
25
+ return stack . length === 0 ;
26
+ } ;
27
+
28
+ describe ( 'Valid Parentheses' , ( ) => {
29
+ it ( 'should return true for valid parentheses' , ( ) => {
30
+ expect ( isValid ( '()' ) ) . toBe ( true ) ;
31
+ expect ( isValid ( '()[]{}' ) ) . toBe ( true ) ;
32
+ expect ( isValid ( '{[]}' ) ) . toBe ( true ) ;
33
+ expect ( isValid ( '([{}])' ) ) . toBe ( true ) ;
34
+ } ) ;
35
+
36
+ it ( 'should return false for invalid parentheses' , ( ) => {
37
+ expect ( isValid ( '(]' ) ) . toBe ( false ) ;
38
+ expect ( isValid ( '([)]' ) ) . toBe ( false ) ;
39
+ expect ( isValid ( '[' ) ) . toBe ( false ) ;
40
+ expect ( isValid ( ']' ) ) . toBe ( false ) ;
41
+ } ) ;
42
+ } ) ;
You can’t perform that action at this time.
0 commit comments