File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
+ import java .util .Deque ;
4
+ import java .util .LinkedList ;
3
5
import java .util .Stack ;
4
6
5
7
public class _1249 {
@@ -37,4 +39,48 @@ public String minRemoveToMakeValid(String s) {
37
39
return sb .reverse ().toString ();
38
40
}
39
41
}
42
+
43
+ public static class Solution2 {
44
+ /**
45
+ * My completely original solution on 10/26/2021.
46
+ */
47
+ public String minRemoveToMakeValid (String s ) {
48
+ Deque <String > stack = new LinkedList <>();
49
+ int left = 0 ;
50
+ int right = 0 ;
51
+ for (char c : s .toCharArray ()) {
52
+ if (c == '(' ) {
53
+ stack .addLast (c + "" );
54
+ left ++;
55
+ } else if (c == ')' ) {
56
+ if (left <= right ) {
57
+ continue ;
58
+ } else {
59
+ right ++;
60
+ stack .addLast (c + "" );
61
+ }
62
+ } else {
63
+ stack .addLast (c + "" );
64
+ }
65
+ }
66
+ left = 0 ;
67
+ right = 0 ;
68
+ StringBuilder sb = new StringBuilder ();
69
+ while (!stack .isEmpty ()) {
70
+ String str = stack .pollLast ();
71
+ if (str .equals (")" )) {
72
+ right ++;
73
+ sb .append (str );
74
+ } else if (str .equals ("(" )) {
75
+ if (right > left ) {
76
+ sb .append (str );
77
+ left ++;
78
+ }
79
+ } else {
80
+ sb .append (str );
81
+ }
82
+ }
83
+ return sb .reverse ().toString ();
84
+ }
85
+ }
40
86
}
Original file line number Diff line number Diff line change 6
6
7
7
public class _1249Test {
8
8
private static _1249 .Solution1 solution1 ;
9
+ private static _1249 .Solution2 solution2 ;
9
10
10
11
@ BeforeClass
11
12
public static void setup () {
12
13
solution1 = new _1249 .Solution1 ();
14
+ solution2 = new _1249 .Solution2 ();
13
15
}
14
16
15
17
@ Test
16
18
public void test1 () {
17
19
System .out .println (solution1 .minRemoveToMakeValid ("lee(t(c)o)de)" ));
20
+ System .out .println (solution2 .minRemoveToMakeValid ("lee(t(c)o)de)" ));
18
21
}
19
22
20
23
@ Test
You can’t perform that action at this time.
0 commit comments