Skip to content

Commit 4ae59e7

Browse files
authored
Update Minimum Remove to Make Valid Parentheses.java
1 parent 55fe8a8 commit 4ae59e7

File tree

1 file changed

+15
-17
lines changed

1 file changed

+15
-17
lines changed

Medium/Minimum Remove to Make Valid Parentheses.java

+15-17
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,25 @@
11
class Solution {
22
public String minRemoveToMakeValid(String s) {
33
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);
1512
}
1613
}
1714
}
18-
while (!stack.isEmpty()) {
19-
chars[stack.pop()] = '-';
20-
}
2115
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));
2523
}
2624
}
2725
return sb.toString();

0 commit comments

Comments
 (0)