forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1249.java
86 lines (83 loc) · 2.62 KB
/
_1249.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.fishercoder.solutions;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;
public class _1249 {
public static class Solution1 {
public String minRemoveToMakeValid(String s) {
Stack<Character> stack = new Stack<>();
int leftParen = 0;
int rightParen = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(c);
leftParen++;
} else if (c == ')') {
if (leftParen > rightParen) {
stack.push(c);
rightParen++;
}
} else {
stack.push(c);
}
}
StringBuilder sb = new StringBuilder();
int diff = leftParen - rightParen;
while (!stack.isEmpty()) {
if (stack.peek() == '(') {
if (diff-- > 0) {
stack.pop();
} else {
sb.append(stack.pop());
}
} else {
sb.append(stack.pop());
}
}
return sb.reverse().toString();
}
}
public static class Solution2 {
/**
* My completely original solution on 10/26/2021.
*/
public String minRemoveToMakeValid(String s) {
Deque<String> stack = new LinkedList<>();
int left = 0;
int right = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
stack.addLast(c + "");
left++;
} else if (c == ')') {
if (left <= right) {
continue;
} else {
right++;
stack.addLast(c + "");
}
} else {
stack.addLast(c + "");
}
}
left = 0;
right = 0;
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
String str = stack.pollLast();
if (str.equals(")")) {
right++;
sb.append(str);
} else if (str.equals("(")) {
if (right > left) {
sb.append(str);
left++;
}
} else {
sb.append(str);
}
}
return sb.reverse().toString();
}
}
}