File tree 1 file changed +15
-17
lines changed
1 file changed +15
-17
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public String minRemoveToMakeValid (String s ) {
3
3
Stack <Integer > stack = new Stack <>();
4
- char [] chars = s .toCharArray ();
5
- for (int i = 0 ; i < chars .length ; i ++) {
6
- if (chars [i ] == '(' ) {
7
- stack .push (i );
8
- }
9
- else if (chars [i ] == ')' ) {
10
- if (stack .isEmpty ()) {
11
- chars [i ] = '-' ;
12
- }
13
- else {
14
- stack .pop ();
4
+ Set <Integer > validIndexes = new HashSet <>();
5
+ for (int i = 0 ; i < s .length (); i ++) {
6
+ if (s .charAt (i ) == '(' ) {
7
+ stack .add (i );
8
+ } else if (s .charAt (i ) == ')' ) {
9
+ if (!stack .isEmpty ()) {
10
+ validIndexes .add (stack .pop ());
11
+ validIndexes .add (i );
15
12
}
16
13
}
17
14
}
18
- while (!stack .isEmpty ()) {
19
- chars [stack .pop ()] = '-' ;
20
- }
21
15
StringBuilder sb = new StringBuilder ();
22
- for (int i = 0 ; i < chars .length ; i ++) {
23
- if (chars [i ] != '-' ) {
24
- sb .append (chars [i ]);
16
+ for (int i = 0 ; i < s .length (); i ++) {
17
+ if (s .charAt (i ) == '(' || s .charAt (i ) == ')' ) {
18
+ if (validIndexes .contains (i )) {
19
+ sb .append (s .charAt (i ));
20
+ }
21
+ } else {
22
+ sb .append (s .charAt (i ));
25
23
}
26
24
}
27
25
return sb .toString ();
You can’t perform that action at this time.
0 commit comments