- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1249.java
85 lines (82 loc) · 2.61 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
packagecom.fishercoder.solutions.secondthousand;
importjava.util.Deque;
importjava.util.LinkedList;
publicclass_1249 {
publicstaticclassSolution1 {
publicStringminRemoveToMakeValid(Strings) {
Deque<Character> stack = newLinkedList<>();
intleftParen = 0;
intrightParen = 0;
for (charc : s.toCharArray()) {
if (c == '(') {
stack.push(c);
leftParen++;
} elseif (c == ')') {
if (leftParen > rightParen) {
stack.push(c);
rightParen++;
}
} else {
stack.push(c);
}
}
StringBuildersb = newStringBuilder();
intdiff = leftParen - rightParen;
while (!stack.isEmpty()) {
if (stack.peek() == '(') {
if (diff-- > 0) {
stack.pop();
} else {
sb.append(stack.pop());
}
} else {
sb.append(stack.pop());
}
}
returnsb.reverse().toString();
}
}
publicstaticclassSolution2 {
/*
* My completely original solution on 10/26/2021.
*/
publicStringminRemoveToMakeValid(Strings) {
Deque<String> stack = newLinkedList<>();
intleft = 0;
intright = 0;
for (charc : s.toCharArray()) {
if (c == '(') {
stack.addLast(c + "");
left++;
} elseif (c == ')') {
if (left <= right) {
continue;
} else {
right++;
stack.addLast(c + "");
}
} else {
stack.addLast(c + "");
}
}
left = 0;
right = 0;
StringBuildersb = newStringBuilder();
while (!stack.isEmpty()) {
Stringstr = stack.pollLast();
if (str.equals(")")) {
right++;
sb.append(str);
} elseif (str.equals("(")) {
if (right > left) {
sb.append(str);
left++;
}
} else {
sb.append(str);
}
}
returnsb.reverse().toString();
}
}
}