File tree Expand file tree Collapse file tree 1 file changed +17
-22
lines changed
solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses Expand file tree Collapse file tree 1 file changed +17
-22
lines changed Original file line number Diff line number Diff line change 1
1
function reverseParentheses ( s : string ) : string {
2
- const res : string [ ] = [ ] ;
3
2
const n = s . length ;
4
- const d = Array ( n ) . fill ( - 1 ) ;
3
+ const d : number [ ] = Array ( n ) . fill ( 0 ) ;
5
4
const stk : number [ ] = [ ] ;
6
-
7
- for ( let i = 0 ; i < n ; i ++ ) {
8
- if ( s [ i ] === '(' ) stk . push ( i ) ;
9
- else if ( s [ i ] === ')' ) {
5
+ for ( let i = 0 ; i < n ; ++ i ) {
6
+ if ( s [ i ] === '(' ) {
7
+ stk . push ( i ) ;
8
+ } else if ( s [ i ] === ')' ) {
10
9
const j = stk . pop ( ) ! ;
11
10
d [ i ] = j ;
12
11
d [ j ] = i ;
13
12
}
14
13
}
15
-
16
- for ( let i = 0 , forward = true ; i < n ; ) {
17
- const ch = s [ i ] ;
18
-
19
- switch ( s [ i ] ) {
20
- case '(' :
21
- case ')' :
22
- i = forward ? d [ i ] - 1 : d [ i ] + 1 ;
23
- forward = ! forward ;
24
- break ;
25
-
26
- default :
27
- res . push ( ch ) ;
28
- i = forward ? i + 1 : i - 1 ;
14
+ let i = 0 ;
15
+ let x = 1 ;
16
+ const ans : string [ ] = [ ] ;
17
+ while ( i < n ) {
18
+ const c = s . charAt ( i ) ;
19
+ if ( '()' . includes ( c ) ) {
20
+ i = d [ i ] ;
21
+ x = - x ;
22
+ } else {
23
+ ans . push ( c ) ;
29
24
}
25
+ i += x ;
30
26
}
31
-
32
- return res . join ( '' ) ;
27
+ return ans . join ( '' ) ;
33
28
}
You can’t perform that action at this time.
0 commit comments