-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMinimumRemoveToMakeValidParentheses.java
42 lines (36 loc) · 1.22 KB
/
MinimumRemoveToMakeValidParentheses.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
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
// https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
public class MinimumRemoveToMakeValidParentheses {
private final String input;
public MinimumRemoveToMakeValidParentheses(String input) {
this.input = input;
}
public String solution() {
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < input.length(); i++) {
char curr = input.charAt(i);
if (!Character.isAlphabetic(curr)) {
if (curr == '(') {
stack.push(i);
} else {
if (!stack.isEmpty() && input.charAt(stack.peek()) == '(') {
stack.pop();
} else {
stack.push(i);
}
}
}
}
StringBuilder result = new StringBuilder();
Set<Integer> set = new HashSet<>(stack);
for (int i = 0; i < input.length(); i++) {
if (!set.contains(i)) {
result.append(input.charAt(i));
}
}
return result.toString();
}
}