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 11package com .fishercoder .solutions ;
22
3+ import java .util .Deque ;
4+ import java .util .LinkedList ;
35import java .util .Stack ;
46
57public class _1249 {
@@ -37,4 +39,48 @@ public String minRemoveToMakeValid(String s) {
3739 return sb .reverse ().toString ();
3840 }
3941 }
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+ }
4086}
Original file line number Diff line number Diff line change 66
77public class _1249Test {
88 private static _1249 .Solution1 solution1 ;
9+ private static _1249 .Solution2 solution2 ;
910
1011 @ BeforeClass
1112 public static void setup () {
1213 solution1 = new _1249 .Solution1 ();
14+ solution2 = new _1249 .Solution2 ();
1315 }
1416
1517 @ Test
1618 public void test1 () {
1719 System .out .println (solution1 .minRemoveToMakeValid ("lee(t(c)o)de)" ));
20+ System .out .println (solution2 .minRemoveToMakeValid ("lee(t(c)o)de)" ));
1821 }
1922
2023 @ Test
You can’t perform that action at this time.
0 commit comments