Minimum Remove to Make Valid Parentheses LeetCode solution in Java

1
class Solution {
2
public String minRemoveToMakeValid(String s) {
3
Stack<Integer> stack = new Stack<>();
4
for (int i = 0; i < s.length(); i++) {
5
char ch = s.charAt(i);
6
if (Character.isAlphabetic(ch)) continue;
7
if (ch == '(') stack.push(i);
8
else {
9
if (!stack.isEmpty() && s.charAt(stack.peek()) == '(') stack.pop();
10
else stack.push(i);
11
}
12
}
13

14
// if(stack.size() == 0) return "";
15

16
StringBuilder result = new StringBuilder();
17
HashSet<Integer> set = new HashSet<>(stack);
18
for (int i = 0; i < s.length(); i++) if (!set.contains(i)) result.append(s.charAt(i));
19

20
return result.toString();
21
}
22
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0