File tree Expand file tree Collapse file tree 1 file changed +19
-21
lines changed Expand file tree Collapse file tree 1 file changed +19
-21
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
- * https://leetcode.com/problems/valid-parentheses
3
- * Time O(N) | Space O(N)
4
2
* @param {string } s
5
3
* @return {boolean }
6
4
*/
7
- var isValid = function ( s , stack = [ ] ) {
8
- for ( const bracket of s . split ( '' ) ) { /* Time O(N) */
9
- const isParenthesis = bracket === '(' ;
10
- if ( isParenthesis ) stack . push ( ')' ) ; /* Space O(N) */
11
-
12
- const isCurlyBrace = bracket === '{' ;
13
- if ( isCurlyBrace ) stack . push ( '}' ) ; /* Space O(N) */
14
-
15
- const isSquareBracket = bracket === '[' ;
16
- if ( isSquareBracket ) stack . push ( ']' ) ; /* Space O(N) */
17
-
18
- const isOpenBracket = isParenthesis || isCurlyBrace || isSquareBracket ;
19
- if ( isOpenBracket ) continue ;
20
-
21
- const isEmpty = ! stack . length ;
22
- const isWrongPair = stack . pop ( ) !== bracket ;
23
- const isInvalid = isEmpty || isWrongPair ;
24
- if ( isInvalid ) return false ;
5
+ var isValid = function ( s ) {
6
+ let stack = [ ] ;
7
+ let map = {
8
+ '}' : '{' ,
9
+ ']' : '[' ,
10
+ ')' : '(' ,
11
+ } ;
12
+ if ( s . length < 2 ) return false ;
13
+ for ( let i = 0 ; i < s . length ; i ++ ) {
14
+ if ( s [ i ] in map ) {
15
+ if ( stack [ stack . length - 1 ] == map [ s [ i ] ] ) {
16
+ stack . pop ( ) ;
17
+ } else {
18
+ return false ;
19
+ }
20
+ } else {
21
+ stack . push ( s [ i ] ) ;
22
+ }
25
23
}
26
- return stack . length === 0 ;
24
+ return stack . length == 0 ;
27
25
} ;
You can’t perform that action at this time.
0 commit comments